Wednesday, June 29, 2011

How to create and read JSON strings in JavaScript

JSON logo and JavaScriptJSON 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 variableJavaScript 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.comWonderWidgetIn 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.

7 comments:

  1. When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four e-mails
    with the same comment. Is there any way you can remove people from
    that service? Thanks a lot!

    My blog; sffronx -
    -

    ReplyDelete
  2. Howdy! Would you mind if I share your blog with my myspace group?

    There's a lot of folks that I think would really enjoy your content. Please let me know. Cheers

    Also visit my blog post: Lift Or Cardio First

    ReplyDelete
  3. I have to thank you for the efforts you have put in writing this website.
    I'm hoping to view the same high-grade blog posts from you later on as well.
    In fact, your creative writing abilities has inspired me
    to get my very own website now ;)

    My webpage: Weight Lifting and Cardio

    ReplyDelete
  4. Hey there! This is my first visit to your blog! We are a collection of
    volunteers and starting a new project in a community in the same niche.

    Your blog provided us useful information to work on.
    You have done a marvellous job!

    Feel free to surf to my homepage Weight Lifting Cardio

    ReplyDelete
  5. Hello! Would you mind if I share your blog with my myspace group?
    There's a lot of folks that I think would really enjoy your content.
    Please let me know. Cheers

    my weblog: pure garcinia cambogia extract

    ReplyDelete
  6. Hi, Neat post. There's an issue with your website in
    internet explorer, would check this? IE still is the
    market leader and a huge portion of other people will
    pass over your excellent writing due to this problem.


    Here is my homepage Weight loss dieting

    ReplyDelete
  7. Hello There. I discovered your weblog the usage of msn.
    That is a very smartly written article. I'll be sure to bookmark it and return to
    learn extra of your helpful info. Thank you for the post.
    I will certainly return.

    my web blog; Yacon Syrup Supplement

    ReplyDelete