Comments in JSON

Comments in JSON

Unfortunately the JSON specification does not allow for comments in the same way that many programming languages do. So while JSON is often closely associated with JavaScript (even though it's used by most other languages as well), it does not support the same commenting features as JavaScript as it's a data-only specification. Comments were removed from the JSON specification because they were being used as parsing directives, which would have hurt interoperability.

While some JSON exporters and parsers do support or ignore comments (like Google's gson), others will not, so it's best to not try and use them unless you're using a custom parser that explicitly ignores comments.

So what are your options if you really need to include comments in your JSON data?

Comments as Data

One option would be to include your comment in a JSON-friendly way, meaning that the comment would be a data property.

{
   "name": "Billy",
   "age": "42",
   "role": "staff",
   "_comment": "Upgrade to admin role after onboarding"
}

You can see that our comment uses the same syntax as the rest of the data, making it a property of the object that can be accessed by whatever program reads it. This is also the most common way to include comments in JSON, which is to prefix the comment property with an underscore, which typically denotes a private property or a property that should not be accessed by other programs.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

The comment doesn't have to be prefixed with a single underscore - it could be prefixed with a double underscore or none. Just as long as your program understands the convention being used.

Use a Preprocessor

Another option would be to add an extra step before ingesting your data. This would be to use a preprocessor that removes comments before passing it on to your application. For example, the JS minification tool, JSMin, can also be used to remove comments from your JSON data.

For example, your JSON might look like this originally:

{
   "name": "Billy",
   "age": "42",
   "role": "staff",
   // "Upgrade to admin role after onboarding"
}

Then, after passing through a preprocessor, it might look like the following, which is valid JSON:

{
   "name": "Billy",
   "age": "42",
   "role": "staff"
}
Last Updated: July 23rd, 2022
Was this helpful?

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms