Finder

A JSON Tutorial. Getting started with JSON using JavaScript and jQuery

Javascript has grown from a way to add interactivity on your page, to a language that lets you perform tasks that once belonged to servers. JSON provides for an easy way to create and store data structures within JavaScript. It’s super popular and a great alternative to XML. JSON stands for JavaScript Object Notation…it’s called that because storing data with JSON creates a JavaScript object. The JavaScript object can be easily parsed and manipulated with JavaScript.

Where XML is arguably easier to read, but notoriously difficult to parse (describe to a computer), JSON makes it a breeze to store data in a format that machines dig. Once you encode the data with JSON, you can read it into a variable which creates an object. Really cool stuff. Let’s take a look.

<script>
    var data={ "firstName" : "Ray" };
    alert(data.firstName);
</script>

See the JSON example on JS Fiddle

Breaking JSON down

First, we create a variable to hold our data, and then we use JSON to define our object. Our sample object above is a simple as it gets. Just an item called firstName and it’s value Ray. When using strings with JSON, you should use them with quotations as above. If you use numbers, then you don’t have to use quotations.

This example will cause your browser to alert you with the variable name.

Creating a JSON object is easy

Creating an object placeholder

That’s great. Let’s go ahead and make it a bit more realistic by inserting our JSON data into an object in the DOM.

<div id="placeholder"></div>
    <script>
        var data={"firstName":"Ray"};
        document.getElementById("placeholder").innerHTML=data.firstName;
    </script>

See the JSON example on JS Fiddle

So now at least we’re putting the data inside an HTML element instead of an alert. The JSON data, of course can be much more complex. Let’s try adding some more fields.

<div id="placeholder"></div>
<script>
  var data={
    "firstName":"Ray",
    "lastName":"Villalobos",
    "joined":2012
  };
  document.getElementById("placeholder").innerHTML=data.firstName+" "+data.lastName+" "+data.joined;
</script>

See the JSON example on JS Fiddle

A couple of things about these changes…First, you’ll see that we added a bit of formatting to our JSON data. That’s just to make sure it’s easier to read for humans; you’ll often find JSON data formatted in this manner. The second thing is that the “joined” value (2012) didn’t need quotations because its a number. That’s still pretty simple data. Let’s try something more complex.

Adding Arrays

What if we wanted to enter a bunch of people…then we have to add array notation. You create arrays in JSON using brackets []. Let’s see how our data would look for a couple of users.

<div id="placeholder"></div>
<script>
var data={"users":[
        {
            "firstName":"Ray",
            "lastName":"Villalobos",
            "joined":2012
        },
        {
            "firstName":"John",
            "lastName":"Jones",
            "joined":2010
        }
]}

document.getElementById("placeholder").innerHTML=data.users[0].firstName + " " + data.users[0].lastName+" "+ data.users[0].joined;
</script>

See the JSON example on JS Fiddle

This looks more complicated, but it’s not really too hard to understand. Every object in jason is stored with curly braces {}, an array is stored with brackets[]. So in order to organize our data, we created an object called users, which held an array (using brackets). That object had a couple of other objects…each stored like before with curly braces {}. Each element in that object was separated by commas.

Notice that we obviously had to change our code for inserting the name. We had to include the new users object and then specify bracket notation to specify our first element in the array. Let’s add another level of complexity to our data structure just for kicks.

<div id="placeholder"></div>
<script>
    var data={"users":[
            {
                "firstName":"Ray",
                "lastName":"Villalobos",
                "joined": {
                    "month":"January",
                    "day":12,
                    "year":2012
                }
            },
            {
                "firstName":"John",
                "lastName":"Jones",
                "joined": {
                    "month":"April",
                    "day":28,
                    "year":2010
                }
            }
    ]}

    document.getElementById("placeholder").innerHTML=data.users[0].firstName + " " + data.users[0].lastName+"--"+ data.users[0].joined.month;
</script>

Simple JSON Output

See the JSON example on JS Fiddle

Just one tiny level of complexity. We just added multiple fields to the joined object. We didn’t need an array here, just a series of objects, so we used the object notation. This is great and we’ve got some pretty good data, but now that we have multiple users, it’s time to go through each user and output them into a list.

Traversing the user list

So, if we want to go through the user list, we could simply use JavaScript’s for statement to take care of that. We’ll put the items inside a list.

<div id="placeholder"></div>
<script>
    var data = { "users":[
            {
                "firstName":"Ray",
                "lastName":"Villalobos",
                "joined": {
                    "month":"January",
                    "day":12,
                    "year":2012
                }
            },
            {
                "firstName":"John",
                "lastName":"Jones",
                "joined": {
                    "month":"April",
                    "day":28,
                    "year":2010
                }
            }
    ]}

    var output="<ul>";
    for (var i in data.users) {
        output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
    }
    output+="</ul>";

    document.getElementById("placeholder").innerHTML=output;
</script>

See the JSON example on JS Fiddle

So here, we use a for statement and created a variable called output to temporarily store the data. Once we go through all of the elements in the array, we use the output variable to populate the placeholder div. That works well, but as you can tell, our data structure is getting a little long.

Reading JSON from an external file

It would be nice if we could store this on an external file and then just read everything into the data variable. To make things easier, I’m going to use jQuery, so we’ll have to load that library first and then call it’s getJSON function. Here’s what our entire page’s code looks like.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
  $.getJSON('data.json', function(data) {
        var output="<ul>";
        for (var i in data.users) {
            output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>
</html>

The resulting output from our final document

Pretty much the same code as before without the data file. We just wrap everything inside jQuery’s getJSON function, which does the hard job of reading the file. Assuming the file is in the same directory here’s what our new data.json file looks like.

{"users":[
        {
            "firstName":"Ray",
            "lastName":"Villalobos",
            "joined": {
                "month":"January",
                "day":12,
                "year":2012
            }
        },
        {
            "firstName":"John",
            "lastName":"Jones",
            "joined": {
                "month":"April",
                "day":28,
                "year":2010
            }
        }
]}

Pretty much as before. As you can see, JSON is really easy to read and once you get used to the curly braces and brackets, not too hard to encode.

48 thoughts on “A JSON Tutorial. Getting started with JSON using JavaScript and jQuery

    1. Tuttos

      Just checking out your jsfiddle and not sure if intentional or not but thought I’d make you aware, when you’re iterating through the JSON data using Jquery.each() you’re actually creating a new unordered list for each individual item. To remedy you would have to implement the articles approach of appending to a var outside the scope of the iteration and then the closing tag afterwards. Thanks for the share though!

      var output = “

        “;

      $(data.users).each(function() { output += “

    2. ” + this.firstName + ” ” + this.lastName + “–” + this.joined.month+”
    3. “; }); output += ““; $(‘#placeholder’).append(output);

      Reply
  1. Alex

    Thanks – great help. Any chance of extending it and showing how to filter results – display just those who joined in 2010/called John.

    Reply
    1. planetoftheweb Post author

      I usually use PHP to handle this. There might be a better way to do it, but I like that PHP will serve up a version of the JSON that is a subset. You can use the jsondecode or jsonencode methods in PHP to handle the parsing.

      Reply
    2. Ray Villalobos Post author

      Another library that works really well for this is underscore.js. It has a bunch of utility functions that do this. You can also use JavaScript regular expressions to take care of it.

      Reply
  2. Marlo

    Thankyou for this tutorial.. this helps me a lot :) what i’am confused now is how can i populate the json object using php

    Reply
  3. Pingback: Introduction to JavaScript Templates with Mustache.js | View Source | The Languages Site

  4. Pingback: Youtube API Tutorial Using Javascript | WEBTUTS

    1. Ray Villalobos Post author

      Check the developer console for errors. If you’re working on a local file, make sure you use Safari or make sure you upload the files to a server. Chrome by default will prevent you from accessing JSON files from your local machine that are on some external server. It should work once you place the files on your server.

      Reply
  5. Pingback: An Introduction to JavaScript templating with mustache.js | lynda.blog

  6. Neil

    Hi Ray, Cameron, Thanks for your article. Simply and clearly explained. I’m new to jquery. How do I read a file containing json using $.getJSON … and process it with the jquery .each method. I have tried several ways including : $.getJSON(‘data.json’).each(function() { … but I can’t figure it out. Thanks. Neil.

    Reply
  7. Neil

    A solution to my question: $.getJSON(‘data.json’, function(data) { $(data.users).each(function() { var output = “

    • ” + this.firstName + ” ” + this.lastName + “–” + this.joined.month+”
    “; $(‘#placeholder’).append(output); }); });

    Neil.

    Reply
    1. Ray Villalobos Post author

      Thanks Neil, I was about to write back on that. I was going to say that you run the each function on the data you get back, not on the data itself. That works as long as the data you get back is an array. It looks like you figured it out. Thanks for posting the solutions so others can see it.

      Reply
  8. Pingback: jQuery summary (I) | TONY'S BIG WORLD

  9. Patrick Murphy

    Thanks for your work on this site and on Lynda as well. I find your tutorials to be priceless as I transition from Flash Builder into Javascript and HTML. I was wondering if you could elaborate on the above tutorial in terms of adding a detail page that gets linked to from one of the list items. For instance, if these were placed in a JQuery Mobile list view and you clicked on John Jones the next page would show the day and year he joined.

    Reply
    1. Ray Villalobos Post author

      Hi Patrick,

      If you’ve got lynda.com, then check out my course on JQuery Mobile Web Applications (http://www.lynda.com/jQuery-tutorials/jQuery-Mobile-Web-Applications/104967-2.html). I show you how to take JSON streams from YouTube, Twitter and WordPress within jQuery Mobile. There’s also a new course on JavaScript and AJAX(http://www.lynda.com/Developer-tutorials/JavaScript-and-AJAX/114900-2.html)…there’s an exercise at the end of that course that works with JSON to create a search app. I’m also working on a new course on JavaScript and JSON where I’ll go into more details on working with the JSON format.

      Reply
      1. Mikey

        Hey Ray, I’ve really gotten a lot of your tutorials from the lynda site and I’ve viewed both of these courses that you mention. I had the same question as Patrick had in the above post. How could you pass from your list view to a details page? From your jQuery mobile applications course you use the WordPress json API to getpost&postid= for the details, how could you do this with a local data.json file?

        Reply
        1. Ray Villalobos Post author

          You would have to build the JSON file so that the data would be in the same file and just output the right data when someone clicks to go to a details page. Alternatively you could use something like underscore.js to parse the JSON feed or create your own PHP solution.

          Reply
  10. Ashish

    Hi, Thanks for this nice code it helps me out but i am unable to fetch data from json when i am writing data-role=”listview” in ul tag kindly help me soon

    Reply
  11. itskevinzak

    Hey Ray cool tutorial. I’m having some trouble with reading it from an external file though. I tried it in Safari, Chrome, and Firefox and couldn’t get it to display. It worked fine when I used your code that had the JSON in it. I just copied exactly what you have for that last code bit and that last JSON file. Am I missing something?

    Reply
    1. Ray Villalobos Post author

      Hey there,

      This is probably due to JavaScript’s same domain policies. AJAX calls have to execute on a server and the HTML file has to be on the same domain. Try loading them both to the same place on a server and it should be fine. You should also try using your developer’s console to make sure things are working properly. You’ll usually see an error that explains things there.

      Reply
  12. Ashish

    Thanks Ray. For a good tutorial for beginner. Hope we will see some more articles for JSOn from iviewsource.com.

    Reply
  13. David

    Hi.

    I was trying to do the same but getting data or file (using $.getJSON) from my jsf project. Do you know a simple example or link. I have been google but no way..

    Thanks for your blog.

    Reply
    1. Ray Villalobos Post author

      I’m not really sure by the message above where you’re having the problem. The biggest culprit is usually the browser same domain policy. I cover JSON in depth in my course JavaScript and JSON on lynda.com if you have a subscription.

      Reply
  14. Pat McG

    Ray, I’ve been going through your lynda.com jQuery Mobile Web Applications. I’m stuck with this error on the wordpress lesson: Uncaught ReferenceError: listPosts is not defined.

    I’ve gone through your example and can’t find where I went wrong.

    Sorry if this isn’t the appropriate place to ask a question, but I really want to move on with this lesson.

    function listPosts(data) { var output=”; $.each(data.posts,function(key,val) { etc. I did this like you said, first seeing if the object was read. I never get beyond the Uncaught ReferenceError: listPosts I also tried with my wp site and still got the error.

    Thanks! I love all your lessons. They’re the best.

    Pat

    Reply
  15. Anton

    mmm…i have a realy nube question. i have an html5 form with submit. i need to take text from the fields, convert it to the json object and send it to the server with “post” method. im really stuck and im trying to find answers by myself.but after two days of trying to uynderstand how it works im still at the same place i started.here some of what i get until now...ill be glad to get an answer for you. function showMe() {

        var mTitle== document.getElementById("title").value;
        var mWriter = document.getElementById("writer").value;
        var mArticle = document.getElementById("article").value;
        var text = {
            "title" : mTitle,
            "writer" : mWriter,
            "article" : mArticle
        };
    
        $.post("http://gammaflow.no-ip.org/tora/createTip/",
                  text,
                  function(data){
                    alert("Data Loaded: " + data);
                  }
                );
    
    }
    

        <input type="text" id="title"> <span>title</span> <br>
        <input type="text" id="writer"> <span>writer</span><br>
        <textarea rows="15" cols="50" id="article"></textarea><span>article</span><br>
        <input type="button"  value="send" onclick="" >
    
    </form>
    

    Reply
    1. imma

      Yes, looks like you need to pass it json, not an object, although replacing “text” with “JSON.stringify(text)” might be enough for your example case – depending on what your server is expecting :-)

      Reply
  16. Pingback: Parsing a external JsonFile - How-To Video

  17. Poorani

    How to get the first object name dynamically… I have to use the same script for various JSON of same type..

    Reply
  18. Morris

    Thank you for this! Its helped me a lot, but I have questions. I am trying to work with a JSON array file, but it doesnt start with the array name. So it looks a lot like the one used here but without the ‘{“users”:’ in the begining and ‘}’ at the end. My code works just fine if I add that part, but I was wondering if there was a way to work with this kind of JSON file.

    Thanks again!

    Reply
  19. Ms.Yuta Lolap

    How do i get a json object which is hardcoded from a java class in javascript on a jsp? What are the prerequisites? DO i have to make a ajax call from the jsp using jquery on which i want to get it from the Java class? Also which framework should i use? Struts ?

    Reply