🧵 From JS object to JSON string and vice versa

const person = { name: 'John', age: 29, hobbies: ['chess', 'football'] };

const personStr = JSON.stringify(person);
// myObjectStr = '{"name":"John","age":29,"hobbies":["chess","football"]}'

const parsedPerson = JSON.parse(myObjectStr);
// parsedPerson = { name: 'John', age: 29, hobbies: ['chess', 'football'] }

If you want to convert a JS object to a JSON string you can use the JSON.stringify method. For the inverse operation, going from a JSON string to a JS object, you can use the JSON.parse method. JSON strings are good for client-server communication and also because they can be converted back to JavaScript objects easily. Note that the only types that are convertible to JSON are: numbers, strings, booleans, nulls, arrays and objects.