12 ms·
Parsing JSON Is a Minefield (2016)
- Decabytes 5y agoI’m a data scientist so I work with JSON and csv all the time. It’s amazing how the back bone of data serialization and reporting are so ambiguous. But I wonder if I’m part of the probably. Know one notices all the inconsistencies because so much of my job is ironing it out.
- jillesvangurp 5y agoUse a decent parser and most of those issues go away. If you do go down the path of writing your own parser, do your homework, obviously. Probably not worth the trouble unless you know what you are getting into. But if you do, maybe run some of the tests that people have produced over the years to produce reports like this.
- Ginden 5y agoHow many of these inputs can be generated by JSON-generating libraries? How many of these inputs can be generated by JSON-generating libraries on accident? 1? 2? How many of these inputs can lead to exploitable vulnerabilities? 1 (duplicated keys handling inconsistencies)?
- Ygg2 5y agoThis is from 2016, no? Why was it reposted? Did something changed significantly?
- IggleSniggle 5y agoReposting doesn’t have the same negative connotation here as it might other places. Sometimes valuable insights come from older works. Sometimes a conversation is worth having on HN with a contemporary context. If it ends up on front page, folks are finding it valuable to discuss.
- Ygg2 5y agoI don't understand the reasoning behind it, and my genuine question has been flagged. Why is it posted now, rather than a year or two years ago?
- IggleSniggle 5y agoI suspect you were flagged for seeming to complain that the submission was inappropriate. See the HN guidelines: https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html Posted now because it is still relevant. Previous posting/discussion: 5 years ago: https://news.ycombinator.com/item?id=12796556 https://news.ycombinator.com/item?id=12796556 3 years ago: https://news.ycombinator.com/item?id=16897061 https://news.ycombinator.com/item?id=16897061 2 years ago: https://news.ycombinator.com/item?id=20724672 https://news.ycombinator.com/item?id=20724672
- peterkelly 5y agoOnly the person who posted it knows exactly why they chose this particular day to do so. Probably they came across it in the course of their work and thought it might be useful/interesting to have a discussion about it. Apparently a lot of other people agreed because they upvoted it. Revisiting old articles every few years can be useful, because the set of people participating in the discussion is likely to be substantially different from those who commented on it the last time it appeared. Those people may have insights or information to share that weren't discussed previously. Maybe some of the people commenting here hadn't even started working in the industry when the original post was made. And even people who were part of the first discussion may have new thoughts on the topic. As an example, while I was certainly aware of and using JSON at the time this article was written, and recall reading it at the time, it is actually much more relevant to me now because I am working on a project that uses JSON in a different way than what I'd done previously. Specifically, we rely on the fact that the same piece of data will always serialize to the exact same string, which we hash and use for later comparisons. We've run into issues relating to interoperability problems between different implementations exactly because of the issues discussed in the article (and yes I'd prefer to use an alternative format for these reasons). This is something I wouldn't have been concerned with at all on previous projects where it didn't matter if there were slight differences. That's just a datapoint on why I personally have renewed interest in this discussion. If you look at a lot of other sites like Reddit (where reposts of articles are often discouraged), you'll often find that on question-based subs, many different people ask the same few kinds of questions with extreme regularity. Subs like /r/askreddit and /r/relationships are full of examples. HN is as much about discussion (if not more) than the actual articles themselves, and as mentioned above such discussions can offer something new each time. So as long as they're not repeated too often, reposts can still have value.
- MrBuddyCasino 5y agoOld articles that consistently do well are periodically re-submitted by accounts that want to farm karma points. Why, I don't know.
- account-5 5y agoCynical and for some maybe true. Or it could be people are genuinely posting something they have just read for the first time and thought others might find it interesting. I count myself in this group; posting and finding this interesting. I do search before posting though others may not.
- petee 5y agoIve resubmitted a post that i knew was on HN a few years prior, but forgot just how eye opening it was at the time and thought that surely some missed it and would appreciate it again. You're probably right some people do it for points, but more likely its just more people fascinated by a specific topic, so more submissions. My repost in particular was the ASCII/binary 4-column representation rather than the typical 3-col, which makes a big difference in understanding
- MrBuddyCasino 5y agoI should have been more elaborate. Your case is of course fine. But I noticed accounts with a very high karma count that submit a huge volume of articles, but hardly any comments. I don’t know exactly what’s going on, but I find it slightly weird.
- kergonath 5y agoResubmitting is one thing, but if it is upvoted, it means that at least some people find or interesting or valuable. If some people do, then resubmitting it was useful.
- MrBuddyCasino 5y agoThis erodes the quality over time, as the platform becomes less useful to regulars and long-time members, and thus dis-incentives investment and care. Every open platform without rules devolves into a porn distributor, so strictly going by „what’s popular“ is problematic.
- GuB-42 5y agoSometimes, articles are reposted because nothing changed significantly. We sometimes get articles from the 19th century that are still relevant today, and it is interesting to see our ancestors perspective on the problem, and an old article on a problem we still have today is a good indication that there is no easy fix and it won't go away anytime soon.
- Ygg2 5y agoOk, but nothing points this is still relevant. Were tests re-run or something? Last update was 3 years ago.
- coldtea 5y agoWe don't need special tests and metrics to point us that this is still relevant. We know it is, and no, nothing has changed since. Beyond this particular case, this is a social link-voting website. If people submit and vote for an older article, it will be in the front page, end of story. Doesn't matter if it still holds or not - it's enough that people found it still interesting to submit and upvote. Some of the better discussions here happen the nth time the same post is on the front page (and some posts get on the top page 5-10 times in a decade). There's also a handy link on HN to show previous submissions of the same post, and the discussions that ensued.
- Ygg2 5y agoOk, but what is the proof nothing has changed? I just see a repost, of a really good article. No test-suit runs, not even a glib message saying "It's year 2021, and nothing in test suite has changed".
- kergonath 5y agoIt’s here because someone posted it, and enough people upvoted it, and not enough flagged it. There is no conspiracy, things just show up on the front page depending on what we collectively want to read. And it is an interesting article, and I hadn’t read it before, so I upvoted it as well. The rule of thumb is that de-posting is acceptable after ~1 year.
- dec0dedab0de 5y agoEdit: After seeing the comments, I checked my REPL history, and the bad data was still there. luckily with the spaces displayed as \040. Turns out the offending space was \240, which makes more sense. Please disregard this comment. If you're curious, the problem stems from stuffing JSON in the description field of an external system to do our own tagging. Someone (me) must have copy/pasted from a screwy source. We were pulling out our hair trying to figure out what was wrong with it, and I just stuck it in the REPL, and saw the offending character was a space. Manually deleted the extra space and it was fine. A quick google showed space was part of the convention, and we were like "woah that's weird how did we never stumble across that before." I am embarrassed that I posted this now. My only excuse is that I just got over Covid, so I'm going with that :-). This was my original comment: After about a decade of using JSON I just discovered the hard way that you can only have one space after the colon between a key and value. Atleast with the python JSON library.
- pythonthecware 5y agoYeah python is not exactly a language for the web. I know fresh grads and inexperienced professors claim otherwise but its not.
- lcrz 5y agoWhat a dumb take.
- pythonthecware 5y agoSays she while having issues decoding json as of 2021.
- sebzim4500 5y agoI don't see any evidence that python has issues decoding json.
- Eikon 5y agoWhat is “a language for the web”?
- deleted 5y ago[deleted]
- onion2k 5y agoMost (all?) the complaints here appear to be that specific libraries fail to implement the JSON spec in the way that the author has interpreted it. Some libraries try to 'help' by parsing things that they shouldn't, and some fail to parse things they probably should. This is why we end up with so many JSON parsing libraries I guess, but it's not really a problem with the format itself, beyond the fact that clearer specs might disambiguate things and lead to less deviation.
- q3k 5y ago> but it's not really a problem with the format itself, beyond the fact that clearer specs might disambiguate things and lead to less deviation. It is a problem, because it's not a spec that can be implemented reliably. Different parsers behave differently on various corner cases not only because of implementation blunders, but also because the standard(s) just let them do whatever. This spectacularly breaks systems that use more than one parser implementation, each slightly implementing the standard slightly differently. One part of some processing/parsing pipeline will let some payload through, while another one will reject it, or even parse it differently.
- horsawlarway 5y agoI disagree (at least mostly). This is a case where the spec is intentionally loose to allow compatibility with a much larger number of machines and use cases. You'll notice most of the cases where the behavior is implementation defined have resource requirements. example: how deep you want to allow nesting depends a LOT on the capabilities of the machine running the code. A sane value for a modern browser is going to be unworkable on an arduino/ESP32/embedded other. Also... if these ambiguities bother you, you probably haven't read the full http spec either. It's riddled with cases where behavior is implementation defined, for exactly the same reasons (resources are required, and you can't assume everyone has the same amount available). Want to take a guess at the maximum length for a url?
- q3k 5y ago> This is a case where the spec is intentionally loose to allow compatibility with a much larger number of machines and use cases. There's plenty that could've been specified with little detriment to small systems: strings are UTF-8 with a well-defined escape sequence set, numbers are always IEEE-754 doubles, messages cannot be nested by more than 128 levels (or some other arbitrary number in this range), repeated fields are not permitted, everything non-compliant must fail the entire parse. Then the only thing left to handle is a maximum serialized size (which can be explicitly implementation or user defined). Set the maximum string length to maximum payload length defined earlier and you're golden. That is then your only difference between implementations. This will work on your Ryzen server and on your ESP8266 or ESP32, and can even be handled on your washing machine microcontroller^W^W^WArduino (with a slowdown for dealing with floating point numbers, but you already have to deal with that). Finally, the spec isn't loose because of some design choice to allow interoperability with more machines: it's loose because it was historically loose (see: JSON business card 'specification' chutzpah, which itself is based on a mess of a programming language that is/was JS), and before it could be formalized to something sensible it got implemented haphazardly by different languages. That doomed the format to forever be underdefined, as anything more strict would render existing implementations non-compliant.
- q3k 5y agoSome other fun facts about JSON, its mainstream implementations and using it reliably: 1. json.dump(s) in Python by default emits non-standards-compliant JSON, ie. will happily serialize NaN/Inf/-Inf. You want to set allow_nan=False to be compliant. Otherwise this _will_ annoy someone who has to consume your shoddy pseudo-JSON from a standards-compliant library. 2. JSON allows for duplicate/repeated keys, and allows for the parser to basically do anything when that happens. Do you know how the parser implementation you use handles this? Are you sure there's no differences between that implementation and other implementations used in your system (eg. between execution and validation)? What about other undefined behaviour, like permitted number ranges? 3. Do you pass around user-provided JSON data accross your system? How many JSON nesting levels does your implementation allow? What happens if it's exceeded? What happens if different parts of your processing system have different limits? What about other unspecified limits like serialized size, string length? My general opinion is that it's extremely hard to reliably use JSON as an interchange format reliably when multiple systems and/or parser implementations are involved. It's based on a set of underdefined specifications that leaves critical behaviour undefined, effectively making it impossible to have 100% interoperable implementations. It doesn't help that one of the mainstream implementations (in Python) is just non-compliant by default. I highly encourage any greenfield project to look into well designed and better specified alternatives.
- appleflaxen 5y ago> look into well designed and better specified alternatives From an end user who knows little about these parsing issues, what alternatives are you happy with?
- EdwardDiego 5y ago> How many JSON nesting levels does your implementation allow? What happens if it's exceeded Haha, I've met a few stack overflows in this area.
- tehbeard 5y agoWhile there's a lot of issues with JSON, this one also applies to any other interchange format that supports nesting, including the much beloved XML. Protobuf might also have this, idk if it does any static analysis for infinite depth.
- cryptica 5y agoIt seems like all the 'problematic' edge cases mentioned can easily be dealt with using runtime type validation and are not the concern of an interchange format like JSON which is (and should be) optimized for maximum flexibility/interoperability. The server should not trust the data inside JSON objects sent by remote clients; there should be some kind of runtime type validation; it's expected that different programming languages might interpret the content of the same JSON object slightly differently for certain unusual edge cases. IMO, as an interchange format, JSON should be allowed to evolve over time; JavaScript has already proven this model to be effective; you can always add features and add flexibility but cannot take away features or remove flexibility.
- eatonphil 5y agoOn the topic of JSON and minefields, what is your experience using JSON5? I'm considered moving to it for configuration files in an application I'm building.
- lifthrasiir 5y agoJSON5 mostly extends JSON's syntax, not its data model (it still doesn't outlaw duplicate object keys for example).
- eatonphil 5y agoThis article is about parsing though so I am mostly asking about that.
- lifthrasiir 5y ago"Parsing" can mean wildly different things indeed. In this case though the article does check duplicate keys and numeric range & precision, so the data model is definitely in question.
- AnthonBerg 5y agoI find it much more pleasant to work with.
- ChrisArchitect 5y agoSurely something newer on this since 2016 Plenty of previous discussion: 2 years ago https://news.ycombinator.com/item?id=20724672 https://news.ycombinator.com/item?id=20724672 3 years ago https://news.ycombinator.com/item?id=16897061 https://news.ycombinator.com/item?id=16897061 5 years ago https://news.ycombinator.com/item?id=12796556 https://news.ycombinator.com/item?id=12796556
- EdwardDiego 5y agoFar easier than parsing Markdown at least.
- bob1029 5y agoFor JSON contracts that are of any reasonable level of complexity (many levels of nesting), I prefer to have the same serializer & strong type system on both ends. A common use case here is serializing dynamic business types as JSON in and out of blob columns. For what its worth, I have had maybe 2 hours total worth of struggles with JSON serialization over the last as many years, and we use it for pretty much everything. The biggest pain point for us is implementation-specific. Refactors of namespaces & dependent assembly names can cause trouble with polymorphic serialization (which can absolutely be secure if used responsibly). The only other pain point experienced is with regard to nullable vs non-nullable fields - again only a problem after a change takes place relative to pre-existing JSON documents.
- kstenerud 5y agoSafety and security are two big reasons why I developed Concise Encoding [1]. The computing and networking landscape today is MUCH more hostile compared to the JSON and XML heyday (with state actors and organized crime now getting in on the action), and it's time to retire them in favor of more secure and predictable formats that are also human-friendly. [1] https://concise-encoding.org https://concise-encoding.org
- belter 5y agoPrevious discussion: 2016: https://news.ycombinator.com/item?id=12796556 https://news.ycombinator.com/item?id=12796556 2018: https://news.ycombinator.com/item?id=16897061 https://news.ycombinator.com/item?id=16897061 2019: https://news.ycombinator.com/item?id=20724672 https://news.ycombinator.com/item?id=20724672
- deleted 5y ago[deleted]
- qualudeheart 5y agoCan copilot parse json?
- SavantIdiot 5y agoI deleted my snarky comment because I want to be more serious. You never know when you hack something quick if it may become a future standard for trillions of handshakes! JSON looks so clean and tidy on that business card, but when you look at both RFCs you realize: ZOMG there is a lot of stuff that needs to be thought out!! There are some purists in this thread who claim it is the parsers' fault. I can almost get behind that, but not 100% because you really do need to be more clear about several things (different types of numbers, different character sets, minimum requirements -and- maximum requirements...) I agree with OP that not including implicit version numbers was an oversight: it looks ugly, but if you're not going to put in all the thought in at the start, at least make a version number required so you can ignore mistakes. Let this document be a lesson to anyone who writes a data schema/grammar that eventually replaces JSON.
- admax88qqq 5y agoI dunno man, serialization in general is fraught with peril. At least the JSON grammar is short and simple. I can't believe people in here are genuinely recommending XML as an alternative. Try standardizinh XML in a 14 page RFC. Yes some things need to be though out, but I can sit down and read the JSON RFC start to finish easily.
- SavantIdiot 5y ago> I dunno man, serialization in general is fraught with peril. I completely agree. And I'm certain I'm using JSON in an unsafe way... somewhere. :)
- Ginden 5y agoAnd many people choose to ignore that number parsing issues can happen in XML too.
- tinus_hn 5y agoIt isn’t too bad, considering how many people on this site are still pining for the worst format in the world: csv
- deleted 5y ago[deleted]
- benibela 5y agoThat is why I maintain my own JSON parser. First I started with the parse from FreePascal's standard library. Then I ran test cases on it, and there were lots of issues I had to patch. First it was accepting all kinds of numbers, so I rewrote it to only accept the numbers from the spec Then it was removing invalid \u escapes, while I needed it to replace them with U+FFFD. Then I needed the unchanged input. Besides the test cases from the article, I ran test cases from the W3C XPath test suite. The W3C has a very odd understanding of JSON. Besides the normal numbers and Unicode U+FFFD replacement, the JSON parser must be able to parse it unchanged. That means, if the input number is like 100 or 1e2, the parser must be able to return that as string "100" or "1e2". Those are different numbers. And there must be a user defined replacement of invalid \u, like you set the replacement to identity and the input is "\uDEAD\u002D\udead", then the parser must parse that as "\uDEAD-\udead" while keeping the case.
- dlsa 5y agoSo many standards, for sure. But... parsing json is actually simple enough. You require those who send you data to comply with specific libraries during export and import. If they send a file which can't be imported then they sent a corrupted file. Bonus if you lock the version. Be as specific as you need to be. There are people who will quibble around "there are thousands of libraries". No there aren't. There's just the N you support. We specify all sorts of details for other aspects of computing. Why wouldn't we specify the data format as well? Change control / configuration management are very useful. This is how you reduce pointless complexity. Nip it in the bud as early as possible. EDIT: Not sure why people disagree with this comment. This is basic data management. Are people really asserting that we are NOT allowed to set a minimum standard? This is also called "setting boundaries".
- jmull 5y agoThis is a big problem for people writing general JSON processors/parsers. But it's not too bad an issue for specific applications/systems using JSON... They need their JSON to be in the correct form to represent their "business objects" (or whatever you want to call your application or system-specific data types), which is already a very restricted subset of JSON that a standard can't help with, and only rarely need to bump up against the oddness JSON has around the edges. (Not that people won't bump up against these issues more than they really need to -- e.g, I recently saw someone trying to rely on multiple keys to mean something specific, which is a fun/interesting idea but is crazy to want to put into production... but good specs won't stop people from wanting to do crazy things.)
- nanoscopic 5y agoJSON parsing isn't as hard as this very detailed article makes it out to be. I've written JSON parsers in Perl, C, and Go. My parsers pass all of the checks mentioned except for the ones regarding encoding and/or escape characters. I intentionally only parse UTF-8. I intentionally don't do any parsing within strings except escaping of the ending double quote. Any string value is passed as is to the user of the library to further parse however they wish. Likewise I store numbers as is in a string and provide helper functions to automatically fetch the numerically parsed value if desired. With those restrictions it becomes very easy to write a JSON parser that works well in any number of languages. I additionally support the following extensions: 1. Both // and /* */ comments 2. Trailing commas optional 3. Commas in arrays entirely optional 4. Hex literals in the form of x.[hex] 5. Custom literals in the form of [type name].[custom literal]