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

Finder

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 JSON 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.

Author: Ray Villalobos

Ray Villalobos is a Staff Author for the Web and Interactive segment at Lynda.com. He loves to teach others about the web.

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

    1. 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);

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

    1. 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.

    2. 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.

    1. 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.

  2. 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.

  3. 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.

    1. 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.

  4. 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.

    1. 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.

      1. 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?

        1. 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.

  5. 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

  6. 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?

    1. 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.

  7. 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.

    1. 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.

  8. 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

  9. 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>
    

Leave a Reply