JSON

The most popular format for data exchange between applications.

Time to read: less than 5 min

Briefly

JSON is the most popular format for data exchange between applications. This format is very similar to JavaScript objects. Objects can easily be transformed into JSON for sending to the server.

How to Write

        
          
          {  "brand": "Apple",  "model": "iPhone 11 Pro",  "isAvailable": true,  "display": 5.8,  "memories": [64, 256, 512],  "features": {    "tripleCamera": true,    "faceId": true,    "touchId": false,    "eSIM": true  }}
          {
  "brand": "Apple",
  "model": "iPhone 11 Pro",
  "isAvailable": true,
  "display": 5.8,
  "memories": [64, 256, 512],
  "features": {
    "tripleCamera": true,
    "faceId": true,
    "touchId": false,
    "eSIM": true
  }
}

        
        
          
        
      

JSON consists of key-value pairs. Pairs are separated by commas — ,, while keys are separated from values by a colon — :. A key can be only a string wrapped in double quotes. The value, however, can be almost anything:

  • A string in double quotes — "I love JSON!";
  • A number — 21;
  • A boolean value — true;
  • An array — [18, true, "lost", [4, 8, 15, 16, 23, 42]];
  • An object — {"isValid": true, "isPayed": false}.

JSON is based on JavaScript but is a language-independent specification for data and can be used with almost any programming language, so it skips some specific values of JavaScript objects:

  • Object methods (functions) — {greetings() {alert("Hello World!")}};
  • Keys with the value undefined{"value": undefined}.

If you need to save JSON to a file, use the .json extension.

How to Understand

JSON is used to receive data from a server. A typical workflow scheme:

  1. Send a request to the server;
  2. Wait for a response;
  3. Receive JSON with a set of data;
  4. Convert JSON into a JavaScript object;
  5. Use the data.

Example:

Open demo in the new window

Converting to JSON

To convert data to JSON code, use the method JSON.stringify(). The method takes the value to be converted as the first argument.

Convert a JavaScript object to JSON:

        
          
          const hero = {  nickname: "BestHealerEver",  level: 7,  age: 141,  race: "Gnome",  isImmortal: false,  things: ["sword", "helmet", "belt"],  money: {    gold: 6387,    silver: 1264,    bronze: 931,    diamonds: 2,  },}console.log(typeof hero)// objectconsole.log(typeof JSON.stringify(hero))// stringconsole.log(JSON.stringify(hero))// '{"nickname":"BestHealerEver","level":7,"age":141,"race":"Gnome","isImmortal":false,"things":["sword","helmet","belt"],"money":{"gold":6387,"silver":1264,"bronze":931,"diamonds":2}}'
          const hero = {
  nickname: "BestHealerEver",
  level: 7,
  age: 141,
  race: "Gnome",
  isImmortal: false,
  things: ["sword", "helmet", "belt"],
  money: {
    gold: 6387,
    silver: 1264,
    bronze: 931,
    diamonds: 2,
  },
}

console.log(typeof hero)
// object
console.log(typeof JSON.stringify(hero))
// string
console.log(JSON.stringify(hero))
// '{"nickname":"BestHealerEver","level":7,"age":141,"race":"Gnome","isImmortal":false,"things":["sword","helmet","belt"],"money":{"gold":6387,"silver":1264,"bronze":931,"diamonds":2}}'

        
        
          
        
      

The result of the conversion will be a string:

        
          
          {  "nickname": "BestHealerEver",  "level": 7,  "age": 141,  "race": "Gnome",  "things": ["sword", "helmet", "belt"],  "isImmortal": false,  "money": { "gold": 6387, "silver": 1264, "bronze": 931, "diamonds": 2 }}
          {
  "nickname": "BestHealerEver",
  "level": 7,
  "age": 141,
  "race": "Gnome",
  "things": ["sword", "helmet", "belt"],
  "isImmortal": false,
  "money": { "gold": 6387, "silver": 1264, "bronze": 931, "diamonds": 2 }
}

        
        
          
        
      

Example of Converting a JavaScript Object to JSON Format

Open demo in the new window

Converting from JSON

You can convert a JSON string to a JavaScript object using the method JSON.parse(). It takes a JSON string as an argument.

Let's try to convert JSON:

        
          
          {  "name": "Luke Skywalker",  "height": "172",  "mass": "77",  "hair_color": "blond",  "skin_color": "fair",  "eye_color": "blue",  "birth_year": "19BBY",  "gender": "male"}
          {
  "name": "Luke Skywalker",
  "height": "172",
  "mass": "77",
  "hair_color": "blond",
  "skin_color": "fair",
  "eye_color": "blue",
  "birth_year": "19BBY",
  "gender": "male"
}

        
        
          
        
      

Using JSON.parse(), we will get a standard object with which we can interact:

        
          
          const json =  '{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male"}'const jedi = JSON.parse(json)console.log(jedi.name)// Luke Skywalkerconsole.log(jedi.gender)// maleconsole.log(jedi.birth_year)// 19BBY
          const json =
  '{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male"}'
const jedi = JSON.parse(json)

console.log(jedi.name)
// Luke Skywalker
console.log(jedi.gender)
// male
console.log(jedi.birth_year)
// 19BBY

        
        
          
        
      

In case the string is not a valid JSON code, the method JSON.parse() will throw a SyntaxError.

In practice

Advice 1

🛠 JSON is very convenient to use for obtaining data over the network. For example, one of the popular weather forecast services, Open Weather, can deliver data in JSON through API. Here is JSON with the weather in London.

🛠 JSON is supported by most programming languages, making it convenient to store configuration information and settings.

🛠 JSON does not support comments; a JavaScript comment // comment will lead to an error.

🛠 Alternative data transmission formats are XML and YAML.

🛠 The most well-known JSON file is the configuration file of the npm package manager - package.json.