Welcome to Tony's Notebook

Introduction to JSON

JSON is a simple idea that can be quite confusing at times. It can be difficult trying to figure out when you need to convert JSON to an object and when you need to convert an object to JSON. In this article you'll see both directions, but first what is JSON?

JSON stands for JavaScript Object Notation. It is a data exchange format that has the same notation as a JavaScript object. I'll take a look at that in a moment, but the most important thing to remember about JSON is it's just a string (with a standard format).

First, let's look at some JavaScript, specifically a JS object:

let o = {
    name: "Fred",
    age: 59,
    hobbies: ['diving', 'stamps', 'coins', 'boardgames']
};

You have three data types there: string, number (in this case integer), and an array (of strings). As a JSON string this would be:

{
    "name": "Fred",
    "age": 59,
    "hobbies": ['diving', 'stamps', 'coins', 'boardgames']
}

JSON format also supports other JSON objects within the structure. So you could have:

{
    "users": [ {"name": "Fred", "id": 1234, "loggedin": true}, {"name": "Jim", "id": 4567, "loggedin": false} ]
}

So this is a JSON object that contains a named value (users) that is an array of JSON objects.

NOTE: JSON data is always in name/value pairs.

JSON data types

JSON supports the following data types:

Note that there is no Date data type.

If you ever want to check the validity of your JSON, you can use the excellent JSON lint. Just paste in your JSON string and click Validate JSON.

Where is JSON used?

The reason JSON is important these days is because a lot of code is written in JavaScript, and people are familiar with the syntax of JavaScript objects. Further, many REST APIs offer JSON as the response format. Sometimes REST APIs will offer you the option of responses in JSON or XML (or some other format), but most people opt for the JSON format response as it's quite easy to work with. You make an HTTP request (API call), and what actually returns to the client-side is a string, in the JSON format. You can also POST data to a server in JSON format, and I'll be looking at that in more detail in another article.

Often your client is written in JavaScript, and so converting that JSON string into something compatible with your code is trivial. There are also libraries for most of the other languages. Essentially these libraries provide two main functions:

  1. Convert a JavaScript object, or other language-specific object (e.g. Python dictionary) into a JSON format string.
  2. Convert a JSON string (typically from a HTTP response) into a language-specific object (e.g. Python dictionary).

Let's look at examples in both JavaScript and Python.

JavaScript

First, let's look at going from an object to JSON:

var o = { name: "Fred", age: 59 };
console.log(o);
var s = JSON.stringify(o);
console.log(s);

This code uses stringify to convert a JavaScript object to a JSON-format string.

You can then go the other way:

var j = JSON.parse(s);
console.log(`${j.name} - ${j.age}`);

This code uses the parse method to turn the JSON-format string back into a JavaScript object.

Python

Now let's look at Python. First, you'll see how to convert a Python dictionary into a JSON-format string:

import json

o = {"name": "Fred", "age": 59}
print(o)
s = json.dumps(o)
print(s)

You need to import the json module. You can then use json.dumps to dump a Python dictionary to a JSON-format string.

If you want to convert a JSON-format string into a Python dictionary:

p = json.loads(s)
print(p)
print(p['name'])
print(p['age'])

Here you use json.loads to load a JSON string into a Python dictionary. This is useful where, for example, you receive a JSON response from a REST API and you want to process that response as a Python dictionary, rather than trying to parse a potentially complex string.

Other

Modules and frameworks may provide convenience methods for dealing with JSON. For example, if you are using the Flask web framework then dictionaries returned from a response method are automatically converted to JSON for you using jsonify().

You can also convert non-dictionary items to JSON if you want to by calling any appropriate JSON method. You can then explicitly jsonify any response object you are returning. For example:

@app.route("/users")
def users_api():
    users = get_all_users()
    return jsonify([user.to_json() for user in users])

In this example, taken from the Flask documentation, the user object is converted to JSON with its to_json method. This would leave you with a Python list of user objects (in JSON format). You then turn the Python list to JSON format array using jsonify.

Summary

JSON is an important data interchange format. You have seen how to convert a language-specific object into a JSON string, and also how to convert a JSON string back into a language-specific object.

References