Change language

What is JSON – An introduction

| | |

JSON or JavaScript Object Notation is a text-based data exchange format based on JavaScript. But it can be used in any programming language. The format was developed by Douglas Crockford.

JSON is used in the REST API. XML can also be used as an alternative, but developers prefer JSON because it is more readable and lighter.

How JSON is structured

Values in JSON can be used as follows:

  • numbers;
  • strings;
  • arrays;
  • JSON objects;
  • literals (boolean values true, false and null).

There is no problem with simple values. Let's deal with arrays and JSON-objects, because we are going to work with them.

JSON-object

A JSON object is an unordered set of key-value pairs enclosed in curly braces { }, and it works just like a dictionary.

The key is the name of the parameter (property) we pass to the server. It serves as a token for the receiving system to understand what we've sent it.

Let's look at a simple example:

{
  "name": "John",
  "age": 26
}

We have passed the value "John" with the key "name", to retrieve this property we need to refer to its key, without which it would be impossible to do so.

The value can be more than just a string or a number. It can also be another object! Or an array, or an object in an array, an array in an object… Absolutely any number of nesting levels!

If we're talking about parameters, only strings are put in quotes, everything else is not.

Line breaks are not necessary. In general, you only need spaces and hyphens for readability, the system can understand without them.

For example, we can write a JSON object in this way, and that's just as well:

{"name": "John","age": 26}

A key is ALWAYS a string, and we take it in quotes anyway.

Keys can be written in any order, because a JSON object is an unordered set of "key:value" pairs.

If I want to refer to "name", how do I say it? In Python, there are two ways to do this:

  • Get the value using the get() method.
  • Get the value by key.

get() vs dict[key].

The difference between these options is that if you access a key that doesn't exist, you'll get a KeyError.

person = {
  "name": "John",
  "age": 26
}
print(person[“last_name”])
>>> KeyError Traceback (most recent call last)
>>> KeyError: 'last_name'

last_name = person.get("last_name")
print(type("last_name"))
>>> NoneType

But if you use the get() method, you will get an empty value:

last_name = person.get("last_name")
print(type("last_name"))
>>> NoneType

This method also has a second passed argument, which will be passed if there is no key:

last_name = person.get("last_name", "There is no last_name")
print(last_name)
>>> 'There is no last_name'

JSON array

The array is enclosed in square brackets [ ]:

["MALE", "FEMALE"]

Inside the square brackets is a comma-separated set of values. There are no keys as in object, so you can only access the array by element number. And that's why in case of an array you cannot swap the data inside. It's an ordered set of values, so order is important.

Values

Any values can be inside an array:

Numbers;

[1, 5, 10, 33]

Strings;

["MALE", "FEMALE"]

Literals;

[true, false]

Arrays;

["MALE", "FEMALE", [1, 5, 10, 33]]

Objects;

[1, {a:1, b:2}, "John"]

Mixture.

[1, "John", true, [1, 5, 10, 33], {"a": 1, "b": 2}]

Well Formed JSON

JSON must be well formed, i.e. syntactically correct.

Rules for well formed JSON:

  • Data is written as "key:value" pairs.
  • Data is separated by commas
  • The object is inside curly braces { }
  • Array is inside square [ ]

To check JSON for syntax, you can use any JSON Validator. I use JSON Formatter, it not only checks for correct syntax but also formats JSON into a readable visual format!

From this:

{"name": "John", "age": 26, "is_married": false, "children": { "name": "Julia", "age": null},"skills": ["Python", "Git", "Django", "Linux"]}

It will do this:

{
  "name": "John",
  "age": 26,
  "is_married": false,
  "children": {
    "name": "Julia",
    "age": null
  },
  "skills": [
    "Python",
    "Git",
    "Django",
    "Linux"
  ]
}

Summary

JSON (JavaScript Object Notation) is a text-based data exchange format based on JavaScript, but can be used in any programming language. It is easily readable by humans and machines. Often used in REST APIs (more often than XML due to better readability and lower weight).

Correct JSON values:

  • JSON object - an unordered set of key:value pairs enclosed in curly braces { };
  • array - an ordered set of values separated by commas. Found inside square brackets [ ];
  • A number (either integer or real);
  • literals true (boolean value "true"), false (boolean value "false") and null;
  • string.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically