JSONJavaScript Object Notation — is a lightweight, human-readable format for exchanging data. Originally derived from JavaScript, it is available for many programming languages, including Java, Python, C#, PHP, and Ruby.

JSON is a natural choice to use as a data format for JavaScript asynchronous operations. The JSON object has two important methods for transforming and storing JSON data: parse() and stringify().

The JSON.parse() method takes a string as input and transforms it into an object. Similarly, JSON.stringify() takes a JSON object and converts it into a string.

Let's have an example:

const jsonObj = {
  id: 1,
  name: 'Hamburger',
  icon: '🍔',
  type: 'Food'
}

// convert JSON object to a string
const jsonStr = JSON.stringify(jsonObj)

console.log(jsonStr)
// '{"id":1,"name":"Hamburger","icon":"🍔","type":"Food"}'

//convert string back to a JSON object
console.log(JSON.parse(jsonStr))
// {id: 1, name: "Hamburger", icon: "🍔", type: "Food"}

These methods are not just limited to JSON objects. You can also use them to transform JSON arrays to strings and vice versa:

const jsonArr = ['🐶', '🦉', '💀', '🦆', '🍕']

const jsonStr = JSON.stringify(jsonArr)

console.log(jsonStr)
// '["🐶","🦉","💀","🦆","🍕"]'

console.log(JSON.parse(jsonStr))
// ["🐶", "🦉", "💀", "🦆", "🍕"]

JSON.stringify()

As name suggests, the JSON.stringify() function transforms a JavaScript object into a JSON string. While sending JSON data from a client to a server, it must be converted into a JSON string. JSON.stringify() can also take two more optional parameters:

  1. replacer - either a function or an array to manipulate the result.
  2. space - either a string or a number.

The replacer function is called for each property in the object and can be used to remove specific values from the returned JSON string:

const user = {
  id: 599,
  name: 'John Doe',
  email: 'john.doe@example.com',
  password: '123abc',
  age: 30,
  address: {
    city: 'New York',
    country: 'United States'
  },
  hobbies: ['Fishing', 'Golf', 'Table Tennis']
}

const str = JSON.stringify(user, (key, value) => {
  // filter-out password from a final string
  if (key === 'password') {
    return undefined
  }
  return value
})

console.log(str)

Here is the JSON string returned by the above code, which does not include the password property:

'{"id":599,"name":"John Doe","email":"john.doe@example.com","age":30,"address":{"city":"New York","country":"United States"},"hobbies":["Fishing","Golf","Table Tennis"]}'

If an array is passed as a replacer, only those properties of the object that exist in the array will be included in the final JSON string:

const str = JSON.stringify(user, ['name', 'email', 'age'])

console.log(str);
// '{"name":"John Doe","email":"john.doe@example.com","age":30}'

Note: The replacer function cannot be used to remove values from an array. If you return undefined or a function, then null is used instead.

A space can be either a string of up to 10 characters or a number between 0 and 10. If a string is specified, it will be used as white space. On the other hand, the number indicates how many space characters to use as white space. Here is an example:

const dog = {
  name: 'Bablu',
  image: '🐶',
  age: '6 months'
}

const str = JSON.stringify(dog, null, '----')

console.log(str)

// "{
// ----"name": "Bablu",
// ----"image": "🐶",
// ----"age": "6 months"
// }"

JSON.parse()

The JSON.parse() function does the opposite. It takes a JSON string as input and transforms it into a JavaScript object:

const str = '{"name":"Bablu","image":"🐶","age":"6 months"}'

const dog = JSON.parse(str)

console.log(dog.name) // Bablu
console.log(dog.image) // 🐶
console.log(dog.age) // 6 months

An optional reviver function can also be passed to transform the object properties before they are returned:

const str = '{"id":99,"name":"Bablu","image":"🐶","age":"6 months"}'

const dog = JSON.parse(str, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase()
  }
  return value
})

console.log(dog.id) // 99
console.log(dog.name) // BABLU
console.log(dog.image) // 🐶
console.log(dog.age) // 6 MONTHS

Trailing commas are not allowed in JSON. So JSON.parse() throws an exception if the string passed as an argument has trailing commas:

JSON.parse('[1, 2, 3, 4, ]');
// Unexpected token ] in JSON at position 13

JSON.parse('{"name": "John Doe", "age": 29, }') 
// Unexpected token } in JSON at position 32

Summary

JSON is a lightweight format for sharing data between a client and a server. It has become a natural choice for making asynchronous requests in JavaScript and many other programming languages.

For transforming and storing data, the JSON object provides two methods:

  • JSON.stringify() takes a JavaScript object as input and transforms it into a JSON string. It can take two optional parameters: replacer and space.
    • The replacer can be either a function or an array used to filter-out values from the resulting JSON string.
    • The space argument is either a number or a string. It is used to control spacing in the final string.
  • JSON.parse() does the opposite. It takes a JSON string and converts it back to a JavaScript object or value. An optional reviver function can be passed to perform a transformation on the object before it is returned.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.