support@90-10.dev

Using JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write for both humans and machines, and is often used to exchange data between the client and the server. It has become a popular choice for modern web applications due to its simplicity and flexibility.

A JSON object is a collection of key-value pairs, where each key is a string and each value can be any valid JSON data type, including strings, numbers, boolean values, arrays, and other JSON objects. The key-value pairs are separated by commas and enclosed in curly braces. Here's an example of a simple JSON string:

{
    "name": "Charlie",
    "age": 30, 
    "city": "London"   
}

The JSON object

JavaScript includes a built-in JSON object with methods for converting objects to and from JSON strings:

const person = {
    "name": "Charlie",
    "age": 30, 
    "city": "London"   
};

const personJSON = JSON.stringify(person);
const backToPersonAgain = JSON.parse(personJSON);

This makes it easy to convert JSON objects to string that can be transmitted via, say, a RESTful web service, where they can "unpacked" back into JavaScript objects.

JSON.stringify replacer

JSON.stringify() can take a second parameter which can be used to specify what properties of the object should be included in the JSON string - this is particularly useful if you want only certain properties to be set to a web endpoint. Here is an example where we "hide" the age 😎:

const person = {
    "name": "Charlie",
    "age": 30, 
    "city": "London"   
};

function replacer(key, value) {
    if(key === "age") {
       return undefined;
    }
    return value;
};


const personJSON = JSON.stringify(person, replacer);
  // personJSON is: '{"name":"Charlie","city":"London"}'