155 points · by todsacerdoti · 5y ago · 245 comments
JSON is something we can (almost) all agree on for dumping loosely specified, human readable representations of data structures. It lets users and client application developers be lazy and not have to learn a new library for our preferred data format. The lack of schemas or validation means we can often get away with wishy-washy, hand-written, plain English specifications, or specifications "by example". It's convenient.
For anything intended to be robust, for serious data interchange, use something else. Anything with support for machine-readable schemas, validation, and robust encoding rules. Binary is preferable but a JSON serialization is still a must-have escape hatch.
And here's a shocking idea... provide your clients with an SDK. It's pretty easy to build one around a multi-language data serialization framework and maintaining an SDK is still easier than maintaining a spec that your clients will probably implement incorrectly.
S-expressions might have caught on for this purpose, but they lacked a killer app (jquery, and later rails). Like JSON, they are easy to parse and easy to generate, but being more loosely-specified than JSON, it's less clear how to map a given S-expression to a native type. As a glue format, JSON feels just right, even if it's a bit picky sometimes (e.g. trailing commas).
For anyone who wants extra features like comments, YAML is the oldest popular format I am aware of that is a superset of JSON. For any new format to succeed, IMO it needs to sufficiently distinguish itself from both YAML and JSON, and not just support a feature set that happens to lie somewhere between the two.
I was doing mostly Perl and Javascript when it caught on, and to this day I have very mixed feelings: it's wasteful of space but still doesn't allow comments; its type system is basically a technical-debt generator; and for all that people still get it wrong pretty often. On the other hand, it's more or less human readable for simple data structures and it's more or less everywhere.
My hunch is that for a new format to take off it wouldn't so much need to not fall between YAML and JSON: it would need to be the default format of something with such super exponential growth that even us oldies would have to use it.
I believe it's hard to explain JSON's popularity and wide adoption without talking about javascript. With javascript, JSON was right from the start an ‘eval’ away from being parsed. The barrier to entry to adopt it simply was never there. Once you start to expose JSON APIs to clients, other servers also start to need to consume data from those servers. Rinse and repeat until you reach mass adoption.
They would not have been loosely-specified if they were specified, like JSON was :-) I mean this is taking things a bit backward. When tools use a data format based on S-exprs, they define more clearly what is or isn't valid (OCaml Dune, Guix, etc.)
E.g. XML has all that, and yet the average use of xml is much more fragile thsn the average use of json. Similarly asn.1 has all that, but does anyone actually like the fact the x509 certs use it? (To be clear, json would definitely not be appropriate for that case either).
- HORRIBLE schema format.
- Very few FOSS libraries, most of which are terrible. I used Lev Walkins asn1c[0], which I patched slightly and coupled with some semi-generic code that walks the generated data structures to emit JSON (for debugging purposes).
Yes, but they all implement the JSON RFC slightly differently, or implement it in a totally non-compliant way.
However, we're coming from XML, which was better defined, and there are also binary "quasi standard" formats like protobuf, so those problems had already been solved.
Yet still "the world" has moved to JSON, which seems to indicate that those problems probably were not all that important for most use cases.
- strongly typed
- ad-hoc or schema (your choice)
- no code generation step
- edit in text, send in binary
"Amazon Ion is a richly-typed, self-describing, hierarchical data serialization format offering interchangeable binary and text representations. The text format (a superset of JSON) is easy to read and author, supporting rapid prototyping. The binary representation is efficient to store, transmit, and skip-scan parse. The rich type system provides unambiguous semantics for long-term preservation of data which can survive multiple generations of software evolution."
Apache Avro has support for parsing and utilizing schemas at runtime, even in C++.
For Apache Thrift you have things like thriftpy: https://thriftpy.readthedocs.io/en/latest/
I'm not aware of a type-safe mechanism for Flatbuffers or Protocol Buffers.
I never got anything out of xml validation either. It just lead to this ridiculously verbose garbage xml that was even less readable with all the namespace, namespace declarations, etc. Very tedious to write manually as well. Also lots of weirdness doing e.g. xpath or xsl transformations against that. The whole SOAP / web services bubble eventually imploded when people figured that you could send tiny json objects instead via REST.
I have many issues. People sending invalid json to my APIs is not one of them. You get a bad request if you do. End of story. Don't don that if you don't like bad requests. It's not a problem that justifies a lot of over engineering.
Json, yaml, toml, hocon, etc. are basically all just variants of attempting to send human editable blobs of information. Fine for apis where all of the requests are created by programs. Unfortunately people also abuse them for things like DSLs that are authored by humans. The real problem there is not using a strongly and statically typed language that simply does not allow illegal things. A schema is just a stop gap solution when you don't have that.
Kotlin is actually great for creating proper DSLs. You get IDE auto-completion and red squiggly lines when you do it wrong. I think Rust also has some nice syntactical constructs for creating DSLs. Typescript might also emerge as a language that is very suitable for that (with maybe a few more features borrowed from Kotlin). Using a non compiled language with weak typing kind of defeats the purpose. Hence the endless ruby but not quite ruby like DSLs for things like puppet.
There is no official JSON schema RFC, there is no official linking between json-schema.org and the JSON RFC. There is no push to make every language that supports JSON to also support a JSON schema system.
Finally, there isn't even a guarantee that all human-readable JSON document specifications can be expressed within a JSON schema in any sensible way.
As a case in point, the python parser breaks the JSON spec already with regards to Infinity/NaN, but then has flags to configure this. See https://docs.python.org/3/library/json.html#module-json
> The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs Infinity, -Infinity, and NaN as if they were valid JSON number literal values:
I think the most correct way to deal with this problem is to get IETF and ECMA to update the JSON standard first. Honestly, comma-after-final-element and comments are such important quality-of-life features that I never understood why they weren't part of the original spec.
On the other hand, it might be easier to just adopt TOML and forget about JSON.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
>Trailing commas in objects were only introduced in ECMAScript 5. As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON.
json was largely `eval`d when it first hit the scene. It was easy to parse because you just received it and `eval`d it directly to parse. worked in every browser. security concerns over time lead to this being rightfully replaced with the JSON object and its associated encoder and decoder.
however, since early javascript didn't allow for trailing commas, neither could JSON if it wanted to be able to be `eval`d.
The only real reason why comments would be problematic is that they are a pain to preserve in a consistent way when editing a file, and thus would require extra work in parsers / serializers. Still, it would be worth the cost imo.
- There is no minimum/maximum number/integer value (or sizes) defined in the RFC [1] - you have no guarantee that a number you emit will be readable by all RFC-compliant parsers, so the only safe option is to emit all numbers as strings. There is also no behaviour mandated for parsers that encounter numbers/integers outside of their supported size range, so you can't rely on any fail-safe behaviour.
- There is no standardized behaviour for repeated dictionary keys (which are allowed but 'discouraged' per spec), and different implementations will treat them in different ways. This is especially painful when trying to build JSON middleware that does a parse/check/modify/emit of arbitrary data.
- Implementations in some languages (eg. Python) are non-RFC compliant by default (`python.dumps` will emit NaN/Inf/-Inf, even though the RFC forbids that), and generally all implementations are similar-but-different-enough to trip you up [2].
All three of these have bitten me in the past when trying to interface with something that spoke JSON, and as such I refuse to design new systems that use JSON as any source of truth.
The whole reason JSON is text-based is to make it human-readable while also enabling data exchange, but the lack of comments works against that goal.
A new mime type doesn’t really help because the parser doesn’t check the mime type, it assumes the programmer did that. I’m not against making a new mime type or specification, but there are already so many and making more doesn’t seem to help. Yes it would be nice if PHP and Python implement the logic for ignoring trailing commas the same way, but 99% of the time that isn’t all that important. Yes there will be cases where it matters and bugs are introduced, but since there already significant differences between JSON parsers I don’t see these kinds of things as making it much worse.
I wish something would done in this area relatively soon though because JS has added a number of features that would make a new JSON much nicer like multi-line strings and BigInts.
I think JSON + comments, commas, template literals, BigInt, NaN, Infinity, and BigDecimals (if/when those land in JS) would be very useful. (It'd be nice to include dates, but that's tricky w/o a literal and because dates)
On the other hand, there is an RFC for JSON where there isn't for Markdown, so it ought to be possible to make use of the usual standards process to formalise a successor to the original JSON which might include some of the very common additions some people always want (trailing commas, comments, proper dates) - that this hasn't happened over the last 15 years suggests really that the problem is actually due to lack of agreement.
I honestly don't want to bash JS, but typing is not it's strength.
(Not affiliated)
I would like to see why the author chose to do yet another format, vs adopt JSON5.
Starlark to solve this exact problem, and is a Python subset so that people don't have to learn something totally new either. It's still turing complete, but at least guaranteed to not have any side effects, or even be able to access anything but an explicitly given execution context.
It also makes it easier for other tools to generate, validate, or output config that feeds into your system. They can do whatever processing they want and emit plain old JSON.
I did this to support hand-writing game data in JSON (e.g. monster stats, campaign dialog scripts) and then converting it to MessagePack at build time [2]. This gives you very high simplicity (no schemas) and excellent performance.
As for trailing comma the only real issue in practice is noisy unified diff output. But for JSON word diff or similar works better in any case when the trailing comma is not an issue.
Comments would only serve to make humans edit the file by hand more than they do now, and to maintain it like a snowflake. You should not be maintaining your data in JSON, it should only be a momentary stop along the way to a more robust data storage system [with a schema].
Optional end commas would only encourage people to use shitty hacks to try to craft JSON without a real parser or encoder, which would 1000% end up with broken JSON all the time, which would then force vendors to support shitty broken JSON.
There's a reason it's designed like it is. Cutting corners is not going to result in better outcomes.
Computer-generated data never needs to include trailing commas or comments.
Really the principal use case here is JSON as human-edited configuration files. In which case I suppose it's nice to have a name like "JWCC", but really it's just two flags for JSON decoding libraries to add (or a single nice combined flag).
So that really would be great IMHO, if you could just call json_decode($json, JSON_ALLOW_JWCC). I don't think we need a new MIME type or anything. But a file extension of ".jwcc" would be a nice convention too.
Also, NaN numbers are an entire features, which they talk about above.
Even if one ultimately needs to keep json document’s human structure (like key order, comments, whitespace nuances), they may create and use more syntax structure-aware library to do that.
Sure. I’m particularly thinking about mvn upgrades or “npm update”, which modify pom.xml/package.json files to upgrade the libraries, after checking rules (non-breaking changes or not, vulnerabilities or latest, etc).
For mvn, libraries never succeeded to modify the pom in-place without wrecking the file format, so mvn upgrades never became a thing. It’s also a demonstration that a DOM with comments in memory doesn’t ensure we can output the file as-is ;)
The text "deliberately removed comments from JSON" links to https://web.archive.org/web/20150105080225if_/https://plus.g... where Doug not only explains the reason, but also a solution which works with the existing standard. It's imperative that the JWCC author explain what they find lacking in Doug's solution - stripping comments before handing off the a JSON parser. A new format is a really weird way to go about fixing a problem that already has a solution.
Without a standard format for comments, you have no reason whatsoever to expect the ad-hoc comments in a JSON file made by anyone who isn't you to be styled like JavaScript comments. And if your response is "then everyone needs to use JavaScript-style comments", well, TA-DA, you've just added comments to the spec. You can't have it both ways.
> It's imperative that the JWCC author explain what they find lacking in Doug's solution - stripping comments before handing off the a JSON parser
If the syntax rules for adding comments are unspecified, then the the syntax rules for what to strip out are unspecified too!
> Without a standard format for comments, you have no reason whatsoever to expect the ad-hoc comments in a JSON file made by anyone who isn't you to be styled like JavaScript comments.
But, since comments are not supported in JSON, you can expect JSON from external sources to contain no comments whatsoever.
That’s precisely Crockford’s point: he didn’t want the format to have a comment syntax that works across different parties so that the only way to use comments is internally, i.e. with a custom comment syntax that you strip before interacting with external sources.
He didn't want. That's great, but using JSON doesn't magically eliminate the need for documenting what things _mean_. Oh, this text isn't just text and is actually a datestamp? Oh, this array isn't allowed to have repeat values? Oh, the valid values for this field are "red", "yellow", "purple", and 5? You could have had that documentation inline. Instead you're forced to have it somewhere else because the need for documentation didn't magically vanish when Crockford waved his wand.
All that eliminating comments accomplishes is needlessly limiting the utility of an otherwise mostly fine format. JSON could have been a good configuration language. Instead it isn't and apparently people have to fight to justify fixing that.
You can expect it, and then you'd be suprised when they do.
See people really want/need comments, and they're gonna implement them anyway in dozens of little parsers/libs, and you're gonna have to deal with files having them anyway...
Indeed.
The only reason JSON is as popular as it is is because JavaScript parses it natively (JSON.parse is defined by the JS spec).
I mean I remember using XML for serialization back in the day and how it made we want to kill anyone who was involved in its creation. JSON won because it’s a great and simple standard and yes because it maps 1:1 to js. It was very popular with people who hated js when it came out too - just because of how much better it was than the other options
Just because he had a reason to give doesn't mean it wasn't a bad reason. His stated reasoning failed with hindsight.
(a) People already do what he thought was preventing (custom parser behavior) by removing comments, (so his choice failed to prevent what he wanted to prevent)
(b) people have already created dozens of JSON parser variants that accept comments, because we really want those. And not just some niche devs - Microsoft and dozens of other big companies have tools that accept JSON + dangling commas + extra comments (so his choice was second-guessed and bypassed anyway, just in ad-hoc ways instead of a better universal one).
It wasn't his place to define whether we get comments or not based on some potential parser abuse. But he did it, and now we're stuck with that decision...
He was writing the specification, of course it was his place to do so. Who else would be in the right "place" to write his own specification that no one was enforced to use.
People still do it, and they still call it JSON. Heck, many JSON parsers, who otherwise work fine with regular JSON still accept it.
Even parsers using a different name like JSONC still allude to the JSON connection - and still are an argument that people found a lack in JSON.
Etymology/originology never produced much benefit over pragmatic non-prescriptive examination of how people use things. If anything, it helped confused the situation with pedantic objections.
(Also, as gets pointed out every time this topic pops up on HN, including multiple times on the submission already, the main demand isn't people wanting to add comments to the JS flowing across the wire, but to config files sitting on disk. Responding to people saying "feature X would help use case Y" by noting how many people are using it for use case Z even without feature X is logically incoherent.)
It's not unlike saying "actual code shouldn't allow comments - you can have a separate preprocessor in your non-code file that strips those out." Sure, you could do that, but all your line numbers would be meaningless and everyone would hate the language from day 1.
Stripping comments before handing off to a JSON parser is not a full solution. For example, if the file has to be augmented with additional data and written out again, the comments would be lost.
A baseless reason is not a compelling reason. Some imagined eventual use is not relevant to the utility and convenience. Interoperability (in this greater undefined sense posited) cannot be maintained via syntax anyway.
> stripping comments before handing off the a JSON parser.
Putting an extra processing step before use of JSON is impractical.
> I removed comments from JSON because I saw people were using them to hold parsing directives
> Putting an extra processing step before use of JSON is impractical.
Care to explain?
Java has not been destroyed, nor any other language that uses injected behavior. Ironically, applying parsing directives are basically another tool being run (similar to a linter) so I'm not sure what he's even getting at when suggesting running yet another tool. This just complicates the ecosystem and is part of what makes javascript seem so primitive in use and syntax. Features that are counterproductive for poorly considered reasons.
Similar thing if you want to inspect a JSON dump into a file.
{<object>} {<object>}
That isn't valid JSON, is it? The Qt JSON parser doesn't handle it.
There are libraries[1] that support parsing it and it's not too hard to do yourself, either. Some fairly popular projects use it to represent multiple responses in a single response body[2].
[1] http://ndjson.org/libraries.html [2] ElasticSearch uses it for msearch response bodys, for example.
This format works great when using Amazon Athena (Presto) against log files written with one JSON object per line.
In fact I've been using JSON with comments and trailing commas in my own projects a lot already, and I imagine lots of other people have converged to the same idea since these are really the only two pain points when handwriting JSON. It's about time we give it a formal name.
{ [1, 2]: "a", [3, 4]: "b" }
'Welcome to Node.js v15.7.0.
Type ".help" for more information.
> { [1, 2]: "a" }
({ [1, 2]: "a" })
^
Uncaught SyntaxError: Unexpected token ','
Thar' be dragons! https://stackoverflow.com/questions/32660188/using-array-obj...However, it's equally true that a better language and object notation would support non-string scalar keys.
However, I don't think it is useful to prod JSON (or a variant) to go in this direction.
If it's a map I'm a bit more unsure how you'd check to find the object (quickly). You're basically getting into the how to store a struct/class as a map key. Either way its a bit more involved than just having json parser return an immutable array and map, and the more I think about it the more edges cases there are.
ob = {...}
somemap[ob] = value
// vs
somemap[ob.id] = value
In languages which allow weak keys in such maps, a garbage collector may even reclaim whole key-value pairs once ob falls out of existence. But to my opinion, in json it is barely useful for a number of reasons. It is more programming technique than data transfer format, and these features (and reference loops) should be encoded at a higher level than json.That would mean your API would need to serve different variants based on the Accept header, and your backend code would need to generate the two different variants.
And then you'd have to question if sending API responses with unused things like comments is actually a good idea given it's entirely wasted data in a production environment.
I suspect few people would use a newer JSON format until it's been available for a long time, and even then they wouldn't use it on big sites.
https://en.m.wikipedia.org/wiki/TOML
Not that there's anything wrong with adding comments and commas to JSON. Call it JSONv2, keep the .json extension and let people bump around upgrading for a bit. It's hardly much of a change but has significant benefits, even outside the config file use. For instance it can sometimes be useful to annotate raw data, and it'd be nice to have that built in. Certainly the commas is a no-brainer.
What’s missing?
That means your json parser either will accidentally parse some strings as dates, or will have to be told which strings are (or even might be) dates, introducing a partial schema, or it will have to leave it to the application to convert strings into dates. Workable? Somewhat, but not ideal, just as not supporting numbers, and leaving string-to-integer-conversion to the application (after all, JavaScript will happily convert strings to integers in eval) would be ‘not ideal’.
Also, are you going to accept 2021-02-23T08:10:19Z, too? Leaving out the seconds, minutes,…? for interoperability, you would have to specify that.
ISO 8601 can represent a simple offset from UTC, but it can’t do a lot of the things that the IANA time zone database can do.
Adding an IANA library to the ISO8601 library (often part of the same lib) has so far solved that problem for me. I’m sure it starts struggling with dates before the early 1800’s though.
Also doesn’t work well if you’re dealing with relativistic effects I think.
Another problem with ISO is the specs aren't freely available, so people will generally guess or refer to old versions, drafts, or RFCs (like RFC 3339)
It absolutely has every benefit you cite.
It's the only ISO spec I know the name of without having to look it up.
The practical approaches are to represent it as time since the Epoch (in floating point) or a string where both sides somehow agree what "03/04/05" means.
All these are allowed according to the ISO standard.
There's a ton of ways to represent booleans, a ton of ways to represent dates, a ton of ways to represent numbers of a ton of different bases, a ton of ways to represent strings of various line-endingness'. It really has caused a significant number of easily avoidable issues in my experience.
All the complexity related to anchors and such is unfortunate, but that’s a problem for parser writers.
The link in the main article convinced me otherwise: https://noyaml.com/
Please review https://news.ycombinator.com/newsguidelines.html.