Quantcast
Channel: Hacker News 100
Viewing all articles
Browse latest Browse all 5394

Adding Comments to JSON - FADE FADE

$
0
0

Comments:"Adding Comments to JSON - FADE FADE"

URL:http://fadefade.com/json-comments.html


Adding Comments to JSON

If you've ever tried to add comments to a JSON file, you'llhavefound thatit's impossible. To clarify, I'm not talking about object literals in javascript, I'm talking about real JSON that a JSON parser can parse.

This is unfortunate, especially in cases where a JSON file is being used a configuration file. It's nice to be able to document your settings.

But I seem to have found a little hack that allows you to do just that.

The Hack

Run the following code in a javascript console to see for yourself.
The example output is formatted like Chrome's console, but the result is the same in node.js or other browsers.

> ({a: 1, a: 2});
=> Object {a: 2}

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence.

> Object.keys(JSON.parse('{"a": 1, "a": 2}')).length;
=> 1;

Believe it or not, it turns out JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in parsed object representation. So our source file might look like something like this:

{
 "api_host" : "The hostname of your API server. You may also specify the port.",
 "api_host" : "hodorhodor.com",
 "retry_interval" : "The interval in seconds between retrying failed API calls",
 "retry_interval" : 10,
 "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
 "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",
 "favorite_numbers": "An array containing my all-time favorite numbers",
 "favorite_numbers": [19, 13, 53]
}

The above code is valid JSON. It's parsed representation looks like this:

{
 "api_host": "hodorhodor.com",
 "retry_interval": 10,
 "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
 "favorite_numbers": [19,13,53]
}

Which means we haven't changed the meaning of the JSON in any way by adding our comments.

I think that's pretty neat. Hope you find it useful someday.

Oh, and if you have a moment, head over to stackoverflow and upvote my answer so other people can find it too.


Viewing all articles
Browse latest Browse all 5394

Latest Images

Trending Articles



Latest Images