What's the use of JSON?

As an aside…

Deep Cloning

JSON supports:

  1. primitive numbers and strings
  2. values true, false and null
  3. objects and arrays built up of the above types, including nested objects and arrays.

As long as your object only contains the above types, you can use a combination of JSON.stringify and JSON.parse to make a deep clone of that object. e.g.

const user = {
    id: 1,
    name: ['Bob', 'Smith'],
    email: 'bob@gmail.com',
    address: {
      street: '1745 T Street Southeast',
      city: 'Washington',
      postalCode: '20020'
    }
}

// serialize and deserialize user object
const deepClonedUser = (JSON.parse(JSON.stringify(user)))

// changes to cloned object only
deepClonedUser.name[0] = 'Robert'
deepClonedUser.address.postalCode = '20050'

Json.stringify can also be quite useful for logging out the properties of an object and maintain the original order.

console.log(JSON.stringify(user, null, 2 /* indentation */))
console.log(JSON.stringify(deepClonedUser, null, 2))

// user
{
  "id": 1,
  "name": [
    "Bob",
    "Smith"
  ],
  "email": "bob@gmail.com",
  "address": {
    "street": "1745 T Street Southeast",
    "city": "Washington",
    "postalCode": "20020"
  }
}

// deepClonedUser
{
  "id": 1,
  "name": [
    "Robert", // <-- only changed on clone
    "Smith"
  ],
  "email": "bob@gmail.com",
  "address": {
    "street": "1745 T Street Southeast",
    "city": "Washington",
    "postalCode": "20050" // <-- only changed on clone
  }
}