What is JSON? An Introduction and Guide 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 JSON.

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.

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.

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 front-end development 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"
  }
}
*/

View on JS Bin

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

View on JS Bin

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;
});

View on JS Bin

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, see MDN or this article on Dynamic Web Coding.

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"

View on JS Bin

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"
  }
}
*/

View on JS Bin

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 wherever I want as valid JSON data.

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

View on JS Bin

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);
});

View on JS Bin

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, 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 article, 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 many 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.
  • json.browse – Online to that lets you browse, prettify, and manipulate JSON from an external source or JSON pasted in. A neat feature is the ability to filter the data based on a keyword.
  • 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.
  • excelJSON – Online tool to convert CSV or TSV to JSON, and JSON back to CSV or TSV.
  • Myjson – A simple JSON store for your web or mobile app.
  • 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.
  • JSON Selector Generator – Paste in some JSON, then click on any part of the data and this tool will tell you the “selector” to use in your JavaScript to access that bit of data.

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.

Conclusion

If JSON was a relatively new concept to you, then I hope this post 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, feel free to post a comment, I’ll be glad to edit the article as needed to ensure its accuracy.

7 Responses

  1. David Kaye:

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

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

    Thank you

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

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

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.