Skip to content

JSON

ts
const obj = { name: 'John', age: 30 }
const jsonString = JSON.stringify(obj)

// {"name":"John","age":30}
console.log(jsonString)

const arr = [1, 2, 3]
const jsonArr = JSON.stringify(arr)

// [1,2,3]
console.log(jsonArr)

const text = '{ "name": "John", "age": 30 }'
const json = JSON.parse(text)

// { name: 'John', age: 30 }
console.log(json)

const failedText = '{ name: "John", age: 30 }'
const failedJson = JSON.parse(failedText)

// <anonymous_script>:1
// { name: "John", age: 30 }
//   ^

// SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)
console.log(failedJson)

const arrayText = '[1, 2, 3]'
const arrayJson = JSON.parse(arrayText)

// [ 1, 2, 3 ]
console.log(arrayJson)