CodeinWP CodeinWP

What is JSON? An Introduction and Tutorial for Beginners

If you’re new to web development and have some basic knowledge of HTML, CSS, and possibly a little bit of JavaScript, a practical area in which to expand your front-end skills is by learning JSON using a JSON tutorial like this one.

But even if you already have a basic understanding of what JSON is and have used it in some of your projects, there might be a few things you weren’t aware of. So in this JSON tutorial and guide, I’m attempting to provide a fairly comprehensive discussion of JSON, its history, and its usefulness. I’ll close with a list of some practical JSON tools that might come in handy in future projects.

JSON Defined

JSON stands for JavaScript Object Notation and it’s a data format. That is, it’s a way to hold bits of information, similar to a database. Although JSON originated outside the ECMAScript specification, it is now closely related to JavaScript with the spec now including a JSON object and many developers incorporating it as a quasi-subset of the language.

Here’s an example of JSON syntax:

{
  "species": "Dog",
  "breed": "Labrador Retriever",
  "color": "Yellow",
  "age": 6
}

As you can see, JSON is a data format that consists of name/value pairs (AKA key/value pairs) in the form of strings. The name/value pairs are separated by a colon and each pair is separated by a comma.

Although JSON originated and is usually most closely associated with JavaScript, many (if not all?) programming languages can generate and read the JSON format. The fact that it’s universal in this way is what has made it so popular as a way to store, parse, read, and share information in web apps and web services.

A Brief History of JSON

As mentioned, JSON originated in association with JavaScript and client-side scripting. Douglas Crockford is the inventor of JSON and he maintains the official JSON.org website where it’s discussed in great technical detail.

JSON.org

The earliest official specification for JSON is the ECMA-404 standard from 2013. But JSON goes back much further than that.

The JSON website was officially launched in 2002 (where it was originally redirecting to Crockford’s website). Yahoo and Google began using JSON as early as 2005 and 2006, respectively, and JSON took off in the years following. Wikipedia’s article has more details on the history, if you want to go into that a little more beyond the scope of this JSON tutorial.

How is JSON Different from a JavaScript Object?

As you can tell from the name, JSON is more or less a JavaScript object. But there are differences. First of all, as the spec explains, “JSON is a text format that facilitates structured data interchange between all programming languages.” So it’s universal, it’s not just a JavaScript thing. In fact, it’s not part of JavaScript at all, it’s just derived from the way JavaScript objects are written.

In terms of the syntax itself, there are a few major differences. First, all names (keys) are represented as strings (i.e. they need to be inside quotes). So the following is not valid JSON:

// not valid JSON, but valid as JS object
{
  foo: "bar"
}

The correct way to write that as JSON is:

// valid JSON
{
  "foo": "bar"
}

Note the use of quotes around the name, or key. Also, note the use of double quotes. While single quotes are fine for JavaScript objects, JSON requires double quotes.

Another area where JSON differs from JavaScript objects is the types of values that JSON can store. According to the spec, a JSON value can be one of the following:

  • Object
  • Array
  • Number
  • String
  • true
  • false
  • null

That’s quite similar to the stuff you can put into JavaScript objects, but since JSON is represented as text, that means you can’t feed it stuff like functions or dynamic date values using Date(). So there are no methods or other functionality in JSON, it’s just text. And this is a good thing because that’s what makes it a universal data interchange format.

It’s also important to note that an entire bit of JSON is technically itself a single valid JSON object, and the object type itself is a way to nest JSON objects as values, similar to how this is done with objects in JavaScript. For example, here is a chunk of JSON with an object nested as one of the values:

// Valid JSON
{
  "species": "Dog",
  "breed": "Labrador Retriever",
  "age": 6,
  "traits": {
    "eyeColor": "brown",
    "coatColor": "yellow",
    "weight": "137lbs"
  }
}

Here the root JSON object has four key/value pairs (“species”, “breed”, “age”, and “traits”); but the fourth value (“traits”) has three more key/value pairs nested as a single value (this is an example of the object value type). And as you probably guessed, you can nest objects like this infinitely. Of course, you should only do this to a reasonable degree.

By contrast, a JavaScript object with a nested object might look like this:

// JS object; not valid JSON
let myAnimal = {
  species: "dog",
  breed: "Labrador Retriever",
  age: 6,
  traits: {
    eyeColor: "brown",
    coatColor: "yellow",
    weight: "137lbs"
  }
}

From that, you should be able to see the differences between JSON and JavaScript objects. The keys are not quoted in the JavaScript version, and in order to make the object useful in JavaScript, the whole thing is placed as a value of a variable.

How Should JSON be Stored?

As you probably guessed, since JSON is basically just text, you can pretty much store it however you want. You can store it in a database, in a separate text file, in client storage (like cookies or localStorage) or even using its own file format using the .json file extension (which is basically just a text file with a .json extension). I don’t know of any limitation on how you can store JSON, but if you do, feel free to mention it in the comments.

Once you have JSON content stored, it’s just a matter of retrieving it and parsing it appropriately. There are different ways to retrieve and parse JSON in different languages, but this being a JSON tutorial for a front-end blog, I’m going to discuss how this can be done using JavaScript.

Using JSON.stringify()

As mentioned, depending on what language you’re using to read the JSON data, you’ll have different tools and built-in functions at your disposal to get access to the JSON data in a convenient way. JavaScript, usefully, has two built-in methods that are part of the ECMAScript specification that allow you to achieve two specific tasks.

Let’s say your application is building or populating JSON data in some way. In order to save the data somewhere, it needs to be converted to a valid JSON string. You can do this using JSON.stringify():

let myJSON = {
  species: "Dog",
  breed: "Labrador Retriever",
  age: 6,
  traits: {
    eyeColor: "brown",
    coatColor: "yellow",
    weight: "137lbs"
  }
};

let myNewJSON = JSON.stringify(myJSON, null, '\t');

/* output of myNewJSON:
{
  "species": "Dog",
  "breed": "Labrador Retriever",
  "age": 6,
  "traits": {
    "eyeColor": "brown",
    "coatColor": "yellow",
    "weight": "137lbs"
  }
}
*/

The JSON.stringify() method takes one mandatory parameter (the JSON you want to convert to a string) and two optional arguments. The first optional argument is a replacer function that you can use to filter out some of the name/value pairs that you don’t want to include. I didn’t filter anything out in my example, so I set the replacer function as null. I wouldn’t normally use null, but I wanted to use the third parameter and it’s required to have the second parameter if you want to use the third.

The third parameter is referred to as a space value. This parameter helps you format the stringified JSON so it’s more readable (using indenting, line breaks, etc). In my case, I used a tab character (represented by \t). Whatever character is used will be inserted once for each indent level. If you use a number for the third argument, this will represent the number of spaces to use for each indent.

Using JSON.parse()

By contrast, if you receive JSON in string format, you can do the reverse using the JSON.parse() method:

let myJSON = '{"species":"Dog","breed":"Labrador Retriever","age":6,"traits":{"eyeColor":"brown","coatColor":"yellow","weight":"137lbs"}}';

let myNewJSON = JSON.parse(myJSON);

// logs a JavaScript object, not a string
console.log(myNewJSON);

In the example above, I’m creating a JSON string manually, which I store in a variable. This is just for demonstration purposes, but in a real-world scenario the JSON may be coming from a third-party source or a separate JSON file.

As you can see, the JSON.parse() method converts the JSON string into a proper object that I can then manipulate and otherwise deal with in my JavaScript. The string passed into JSON.parse() is the only mandatory argument, but you have can also add an optional second argument, which is referred to as a reviver function. Here’s an example that assumes the same string is being used as in the previous code:

let myNewJSON = JSON.parse(myJSON, function (name, value) {
  if (name === "species") {
    value = "Cat";
  }
  return value;
});

That’s just a simple example that alters one of the values for one of the names. For more info on the use of the reviver function, which I’m not going into more in this JSON tutorial, see MDN or this article on Useful Angle.

Using JavaScript to Manipulate JSON

As you might have figured out, once you’ve converted string-based JSON data into a JavaScript object, you then have access to that object in the same way you would any JavaScript object. For those already familiar with using JavaScript objects, this will be familiar.

Let’s assume you’ve parsed a JSON string and the myNewJSON variable holds the result, as shown in the previous section. You can now use what’s often called dot notation to access the different parts of the JSON data:

console.log(myNewJSON.species); // "Dog"
console.log(myNewJSON.breed); // "Labrador Retriever"
console.log(myNewJSON.age); // 6

I can also access the nested object and the values inside the nested object by going deeper with dot notation:

console.log(myNewJSON.traits);
/*
[object Object] {
  coatColor: "yellow",
  eyeColor: "brown",
  weight: "137lbs"
}
*/

console.log(myNewJSON.traits.coatColor); // "yellow"
console.log(myNewJSON.traits.eyeColor); // "brown"
console.log(myNewJSON.traits.weight); // "137lbs"

You can do whatever you want with this data. You can add new values, change current values, or even delete entire name/value pairs:

myNewJSON.age = 7;
delete myNewJSON.traits.weight;
myNewJSON.traits.cuddly = true;

console.log(myNewJSON);

/*
[object Object] {
  age: 7,
  species: "Dog",
  breed: "Labrador Retriever",
  traits: [object Object] {
    coatColor: "yellow",
    cuddly: true,
    eyeColor: "brown"
  }
}
*/

In the above code, I changed the age value, deleted the weight property of the traits object, and added a new cuddly property to the traits object.

I can then use JSON.stringify() to convert this new data back into the correct format so I can store it as valid JSON data wherever I want.

Is JSON Better Than XML?

Although XML is certainly not a defunct data format, JSON has largely taken over in popularity. Douglas Crockford explains many of the advantages of JSON over XML, and I’ll quote part of his document here:

XML is not well suited to data-interchange, much as a wrench is not well-suited to driving nails. It carries a lot of baggage, and it doesn’t match the data model of most programming languages. When most programmers saw XML for the first time, they were shocked at how ugly and inefficient it was. It turns out that that first reaction was the correct one. There is another text notation that has all of the advantages of XML, but is much better suited to data-interchange. That notation is JavaScript Object Notation (JSON)

He goes on to discuss the claimed advantages and benefits of XML while showing why JSON equals and betters those advantages.

What is JSONP?

JSONP (meaning “JSON with Padding”) is a solution that attempts to overcome the cross-origin restrictions and limitations that come with fetching data from another server. You may have run into this when attempting to use Ajax or the Fetch API to request data from an external source. Simply put, you can’t do this, for security reasons.

As a solution to this problem, Bob Ippolito first proposed JSONP back in 2005 shortly after George Jempty proposed something similar called JSON++.

JSONP takes advantage of the fact that <script> elements are not bound by cross-origin limitations. That’s why we’re able to link to scripts on remote CDNs with no problems.

Here’s an example that accesses JSONP data using plain JavaScript:

function doJSONP(result) {
  console.log(result.data);
}

let script = document.createElement('script');
script.src = 'https://api.github.com/users/impressivewebs?callback=doJSONP'

document.getElementsByTagName('body')[0].appendChild(script);

This code creates a <script> element, adds a specified URL as the src attribute, then appends the script to the document. In this case, I’m accessing a specific user’s data on GitHub (my own data, actually), using GitHub’s API. If you open up the demo you’ll see the display of the JSON data in the console.

If you’re using jQuery, you can make a similar request using jQuery’s $.getJSON() method:

$.getJSON('https://api.github.com/users/impressivewebs', function (result) {
  console.log(result);
});

Note that in this case, the data I want is exactly what’s returned. In the vanilla JavaScript version, however, I have to drill down into the data property to get the JSON data I want.

In either case, after getting the resulting data, I can use the dot notation discussed previously to access the different name/value pairs. For example, I can get my follower count on GitHub, my Avatar URL, number of public repos, and lots more.

How Does JSONP Work?

To understand how JSONP works, you first have to understand that a plain JSON file cannot be used in this way unless the server sets up the data to respond correctly. In other words, you can’t do this with any external .json file you find online. So how does the JSONP technique resolve this?

In the vanilla JavaScript example in the previous section of this JSON tutorial, you probably noticed the GitHub API URL had a parameter attached to it: callback=doJSONP. This is a callback function that acts as a wrapper (or “padding”) that allows access to the data, because normally when you inject JSON data using a <script> element, it will do nothing because the contents aren’t stored in a variable that can be accessed in your JavaScript.

With JSONP, instead of this:

{
  "one": "value_1",
  "two": "value_2"
}

You’re actually getting this:

callback({
  "one": "value_1",
  "two": "value_2"
});

Where callback would be the name of the callback. In my example it would be doJSONP.

So when you set up the JSON to be accessed on the remote server, you have to ensure that it’s sent with the padding (i.e. the wrapper function). You can see an example in this CodePen where I’m trying to access this game data from Major League Baseball but the browser console says “Uncaught SyntaxError: Unexpected token :”. This is because Major League Baseball hasn’t set up that data to be JSONP accessible.

A detailed discussion of how to set up a JSONP service is beyond the scope of this JSON tutorial, but a simple solution is explained in this Stack Overflow thread.

There are some security concerns associated with JSONP, so be sure to do some research if you are planning to set something up. For more info on JSONP, see the links below:

JSON Tools

There are lots of useful tools for doing different things with JSON data. Below I’ve compiled a list of some of the ones I’ve come across.

  • JSONLint – A validator for JSON data. This is a good tool for learning the basic syntax and how it differs from JavaScript object syntax.
  • JSONedit – A visual JSON builder that makes it simple to build complex JSON structures with different data types.
  • JSON Schema – A vocabulary that allows you to annotate and validate JSON documents.
  • JSON API – A specification for building APIs in JSON.
  • CSVJSON – CSV and SQL to JSON converter and beautifier.
  • JSON Formatter – Online tool to validate, beautify, minify, and convert JSON data.
  • jsonbin.org – A new project from Remy Sharp, “a personal key/value JSON store as a service. Protected behind authentication and API key requests, data is stored as JSON and can be deep linked.”
  • Kinto – A generic JSON document store with sharing and synchronisation capabilities.
  • JSON Generator – Online tool to generate random JSON data.
  • Hjson – A syntax extension for JSON, to help make it easier to read and edit for humans, before it’s passed to a machine.

For more tools like these, subscribe to Web Tools Weekly and feel free to reach out or comment if you’ve got a JSON tool you’d like to share.

Wrapping Up This JSON Tutorial

If JSON was a relatively new concept to you, then I hope this JSON tutorial for beginners has given you a decent overview of what it’s all about. JSON is a solid technology that’s easy to use and powerful because of it being universal.

If you’ve got anything to add or correct in this JSON tutorial, feel free to post a comment, I’ll be glad to edit the article as needed to ensure its accuracy.

31 Responses

  1. David Kaye says:

    DuckDuckGo shows a JSON Beatifier & Validator at the top of “json format” or similar searches:
    https://duckduckgo.com/?q=json+beautifier&t=h_&ia=answer

  2. TaoQuixote says:

    In the part of “Using JavaScript to Manipulate JSON”, there is a word “mested”. “I can also access the mested object and the values inside the nested object by going deeper with dot notation:”, i guess it maybe is “nested”?

    Sorry for my awful English.

  3. John says:

    I thought JSON programming like JavaScript but there are some differences between them

    Thank you

  4. Rachel says:

    I didn’t know too much about JSON before reading your walkthrough Louis; it’s very clear and much appreciated.

  5. Hemant Dave says:

    Useful article. most of the technologies uses JSON so far. Quite great content.

  6. Subhashree says:

    I am learning HTML, CSS, C, PHP. Now I want to learn JSON. Thank you for sharing such a great beginner guide.

  7. baldwin jackson says:

    Thanks for sharing

  8. Chris says:

    Thanks for this. Have you thought about putting your walkthrough on youtube? There’s very little JSON content right now, and none is as high quality as your explanation. Much appreciated.

  9. Miyavi says:

    I’m a web designer who knows html and css. This is pretty helpful for me to up my skills in coding. What additional content would you suggest beginners to read?

  10. Ranjan says:

    The format is designed to be easily human-readable, and should also be immediately parsable by all common JSON parsers.

  11. Bel says:

    Hi, thanks for the explanation. I have a question, I want to put the json data in a listview instead of printing it in a console.log. I created a label in the listview with {{}} but it doesn’t find the variable. I hope I explained myself enough. Thank you!!

  12. Syd says:

    Thanks for the very clear walk through Louis. It’s now my first port of call when I’m teaching new devs on using JSON properly.

  13. Renson says:

    Useful article. most of the technologies uses JSON so far. I use https://onlinejsoneditor.com and https://onlinejsoneditors.com to deal with all my json stuff.

  14. salena says:

    thanks a lot this guide help me alot i have been studying json from a long time and i never found i blog like yours.

  15. aahhh, its JSON syntax is much easier than xml. Thanks for this piece.

  16. jhon dsx says:

    wow! a long explanation! superb !

  17. You saved my many hours, JSON makes life easier.

  18. Sam says:

    Great Explanation, Thank you for this nice post.

  19. Suraj says:

    Nice Explanation Louis… I’m new to JSON and this is very helpful for me. Thanks, buddy…

  20. Danny says:

    JSON object’s standard structure makes the developers job easy to read and write code.

    Good and simple introduction to json, it would be very useful for those who wants to learn about json.

  21. arnav sharma says:

    Thanks for sharing the very clear walkthrough.

  22. shiv says:

    I am very much experience with json using in Google charts

  23. Jay thhoms says:

    Thanks for sharing the very clear walkthrough.

  24. Senthil Nath says:

    Nice information. Good and simple introduction to json.

  25. Thanks for the thorough explanation, Louis. When I’m educating new developers on how to use JSON correctly, it’s now my first stop.

  26. Very detailed explanation, I was learning javascript and JSON was a bit difficult to grasp. thanks for this article.

  27. Deepa Negi says:

    Great explanation, Louis! As a JSON newbie, this is incredibly helpful.

  28. Rudra Rawat says:

    I appreciate the practical approach of this tutorial. It’s perfect for someone like me who has a basic knowledge of HTML, CSS, and a little bit of JavaScript. Learning JSON seems like the logical next step, and this tutorial is just what I needed. Thank you for sharing your knowledge!

  29. Deepa singh says:

    Louis, your comprehensive explanation has become my go-to resource when I’m guiding new developers on the proper utilization of JSON. It’s now the primary reference point in my educational sessions. Your insights have not only deepened my understanding but have also proven invaluable in effectively conveying the intricacies of JSON usage to those just starting in the field. Thanks for providing such a thorough and insightful resource that has significantly enhanced my teaching materials.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).