Introduction to JSON

With JavaScript we typically manage, store and pass around data via objects. However, there comes a time when you need to use data outside of JavaScript, either by sending (or retrieving) it from a web service, or perhaps by storing it locally in the browser.

Where XML is notoriously difficult to parse in some cases, using JSON (JavaScript Object Notation) to store our JavaScript objects in the form of a string, it makes it lots easier to read and parse data.

Taking a simple JS object (in literal expression notation):

we can easily stuff it into a string:

You will notice JSON is broken down into a key/value pair wrapped in quotes. The data types can only be strings, numbers, objects, arrays Booleans or null.

Parsing JSON

JSON can be parsed by using the eval function or the JSON.parse function.

Using eval has some potential security risks, since someone could theoretically include a script inside some JSON data. JSON parse is considered to be more secure, but it’s less compatible with older browsers.

There is another function called JSON.stingify that does the opposite of parse. Sometimes it’s useful to take an exiting JavaScript object and convert it to a string. Though a library like jQuery  can take care of compatibility and parsing for you.

For the most part, when you’re working within  an existing JavaScript file, you’ll be working with JavaScript objects or JSON data that has been parsed into an object. It’s rare to write pure JSON within JavaScript. JSON will be more useful when  reading data from another source.

Creating simple data

Multiple values are separated by a comma, and you can use whitespace for clarity. You do not use quotes for numbers, true or false or null. You can have an array to store multiple values or use a nested object contained within brackets.

Retrieving values

You can use normal dot notation to retrieve values:

Reference: http://www.jsonexample.com/

Tools to validate

The format for JSON & JavaScript objects is  super simple: just a bunch of commas, semicolons, a bracket every now and then. However, it’s super easy to make a mistake, so using an online validator is a good idea such as JSONLint, JSHint and JSON Editor Online to check your JavaScript and JSON syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *