Wednesday, June 29, 2011

How to create and read JSON strings in JavaScript

JSON logo and JavaScript JSON might be a simple format, but it's obviously fairly tedious to write JSON strings by hand. What's more, you often need to be able to take a JSON string, and convert its contents into a variable that can be used by your code.

Fortunately, most programming languages give you tools that can easily turn variables into JSON strings, and vice-versa. The basic idea is as follows: To create a JSON string, you start with a variable containing some data, then pass it through a function to turn that data into a JSON string. To read a JSON string, you start with a JSON string representing some data, then pass it through a function to create a variable containing the data. Let's take a look at how to create and read JSON strings in JavaScript.

Creating a JSON string from a JavaScript variable JavaScript contains a built-in method, JSON.stringify(), that takes a JavaScript variable and outputs a JSON string representing the variable's contents. For example, let's create a JavaScript object containing our cart data from earlier, then create a JSON string from that object:

This produces the output: {"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com", "contents":[{"productID":34,"productName":"SuperWidget","quantity":1}, {"productID":56,"productName":"WonderWidget","quantity":3}], "orderCompleted":true}

Notice that JSON.stringify() outputs JSON strings with all whitespace removed. It's harder to read, but it makes the string more compact for sending around the web. Creating a JavaScript variable from a JSON string

There are quite a few ways to parse a JSON string in JavaScript, but the safest and most reliable way is to use JavaScript's built-in JSON.parse() method. This takes a JSON string and returns a JavaScript object or array containing the JSON data.

Here's an example: Here we've created a variable, jsonString, that holds the JSON string for our shopping cart example. Then we've passed this string through JSON.parse() to create an object holding the JSON data, which we store in cart.

We then check the conversion worked by displaying the contents of the object's shopperEmail property, as well as the value of the productName property of the second object in the contents array.

This displays the following output: johnsmith@example.com WonderWidget In a real-world online store application, your JavaScript would likely receive the shopping cart JSON string as an Ajax response from a server script, pass the string to JSON.parse(), then use the data in the resulting object to display the cart to the user in the page.

No comments:

Post a Comment