JSON JavaScript Methods

Working with JSON in JavaScript

JSON.parse()

const jsonString = '{"name":"John","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); # "John"

JSON.stringify()

const obj = { name: 'John', age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); # '{"name":"John","age":25}'

Pretty Print

JSON.stringify(obj, null, 2); # indented with 2 spaces
JSON.stringify(obj, null, '	'); # indented with tabs

Replacer Function

JSON.stringify(obj, (key, value) => {
    if (typeof value === 'string') {
        return value.toUpperCase();
    }
    return value;
}); # transform values

Reviver Function

JSON.parse(jsonString, (key, value) => {
    if (key === 'date') {
        return new Date(value);
    }
    return value;
}); # transform parsed values

Filter Properties

const obj = { name: 'John', age: 25, password: 'secret' };
JSON.stringify(obj, ['name', 'age']); # only include specified keys