JSON Comments

The JSON spec does not define a syntax for comments even though you’ll often want to comment in your JSON. Author of the spec Douglas Crawford recommends including your comments in the source JSON file and running it through JSMin to produce valid JSON. This bothers me because I hate the thought of having to build JSON. JSON is so simple. It adds a layer of complexity we don’t need.

Here’s a method for commenting on your JSON without breaking with the spec. Take this JSON:

{
  "image": "image.jpg"
}

We want to comment this image to ensure anyone reading the file doesn’t try to display this image to users. Here’s how we’ll accomplish this.

{
  "image": {
    "data": "image.jpg",
    "_comment": "This image should not be displayed"
  }
}

This method assumes you have control over the JSON schema. If you maintain the application that will consume the JSON, you will need to update it to read the data key. That means jsonFile.image in your application becomes jsonFile.image.data instead.

If the application you’re writing the JSON for is not yours and you can’t modify it, this probably won’t work. In this case, you might need to use a slightly different technique that isn’t quite as nice.

{
  "image": "image.jpg",
  "_image_comment": "This image should not be displayed"
}

This method may not work if you run it through an application that validates the input schema, so you’ll want to be sure you test this before you call it done.

Get my web development tips in your inbox!

Enter your name and email, and I'll send you more tips like this one as soon as they go live on the site!

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit

Post a question or comment