Working With JSON

I’ve a big fan of JSON as an alternative to XML when doing client-server communication with JavaScript. For those unfamiliar with JSON, it’s essentially a way of representing data using JavaScript object and array literals (full description) first proposed by Douglas Crockford. Now, it’s starting to gain some popularity.

The basic idea is that you can define data in JSON and just pass it into the eval() function in JavaScript to create the objects and arrays that are described in it. For example, a JSON array of colors is defined as:

["red", "blue", "black"]

You can then pass this directly into eval() to create the array:

var aColors = eval("["red", "blue", "black"]")

You can also represent objects in object literal notation:

{ name: "Nicholas C. Zakas", homepage: "https://humanwhocodes.com/"}

What I just discovered is that you can’t pass this directly into eval() like this:

var oPerson = eval("{ name: "Nicholas C. Zakas", homepage: "https://humanwhocodes.com/"}")

Try this yourself, you’ll get an error in any browser. The problem is that the eval() function is treating the curly braces as indicative of a code block instead of an object literal. At first, this really annoyed me, but I discovered that it’s actually pretty logical. The object literal notation takes affect only when the interpreter sees an assignment, otherwise it considers the curly braces to be a code block. The solution is to include the assignment in the text itself to force the interpreter to realize that it’s an object literal:

eval("var oPerson = { name: "Nicholas C. Zakas", homepage: "https://humanwhocodes.com/"}")

This works perfectly well in all browsers.

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-world uses of promises.

Download the Free E-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.