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 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>
• 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>
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.
Nice tutorial, it helped me out with this JSON business. I played around with your fiddle a bit and reworked it into a more traditional jQuery format — i.e. replace for with .each(), etc.
http://jsfiddle.net/ccnokes/XcpGN/377/
Thanks!
Sometimes I regress to JavaScript when in jQuery…poor upbringing I guess.
Nicely done. .each or for works fine.
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 += “
Yes, the user submitted example does make the UL tag repeat for each statement, which wouldn’t be as efficient.
Yeah, perhaps this would have been better as a JSFiddle.
Thanks – great help. Any chance of extending it and showing how to filter results – display just those who joined in 2010/called John.
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.
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.
Thankyou for this tutorial.. this helps me a lot
what i’am confused now is how can i populate the json object using php
PHP has some great methods you can use for that… jsonencode and jsondecode. Should help you with that. http://php.net/manual/en/function.json-encode.php
can you populate the json data object from an external HTTP get ?
You can do it easily with jQuery’s getJSON method (http://api.jquery.com/jQuery.getJSON/), but if you’re coding locally you won’t be able to see the results if you’re using Chrome. It will work fine uploaded to a server, but not while you preview it. Safari works fine…don’t know about the rest.
Pingback: Introduction to JavaScript Templates with Mustache.js | View Source | The Languages Site
Pingback: Youtube API Tutorial Using Javascript | WEBTUTS
I’m stucked with the external file linking, the data would not display. I’m trying it with notepad++
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.
Pingback: An Introduction to JavaScript templating with mustache.js | lynda.blog
it’s a great tutorial for me………but i wanted to know that how we use json url in html using javascript or jquery……. my url is ” http://siliconsoftwares.in/store/storejson.php” how i parse this json url in html….plz help me……….really thankful to u………
The process should be exactly the same, but you need to understand the structure of your data instead of mine.
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.
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.
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.
Pingback: jQuery summary (I) | TONY'S BIG WORLD
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.
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.
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?
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.
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
Can you elaborate on what the problem is? simply writing data-role=”listview” shouldn’t prevent you from reading a JSON file.
maybe you need to put quotes around “data-role” (or escape the ones on \”listview\” if they’re internal to a value)
A lot of problems with JSON happen because of the Same Domain policy, so make sure your JSON file and HTML document are both on the same server.
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?
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.
Thanks Ray. For a good tutorial for beginner. Hope we will see some more articles for JSOn from iviewsource.com.
Thanks Ray:D
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.
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.
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
I can’t really tell by the code above. Can you send me a link to where I could see this? It looks like it can’t find the variable properly.
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. i
m really stuck and i
m 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...i
ll be glad to get an answer for you. function showMe() {You should try jQuery’s serializeArray function. http://api.jquery.com/serializeArray/ Stack overflow has some good comments on this. http://stackoverflow.com/search?q=convert+form+data+to+json+object
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
Pingback: Parsing a external JsonFile - How-To Video
How to get the first object name dynamically… I have to use the same script for various JSON of same type..
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!
Great Tuotirial ! Buddy Bundle of thanks its clear allk about json for me.
Did u have any link so may i found working with json and asp classic 3.0.
Thanks Gaain, Rizwan Waris
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 ?