Parsing with a reviver function
suggest changeA reviver function can be used to filter or transform the value being parsed.
const jsonString = '[{"name":"John","score":51},{"name":"Jack","score":17}]';
const data = JSON.parse(jsonString, (key, value) =>
key === 'name' ? value.toUpperCase() : value
);
This produces the following result:
[
{
'name': 'JOHN',
'score': 51
},
{
'name': 'JACK',
'score': 17
}
]
This is particularly useful when data must be sent that needs to be serialized/encoded when being transmitted with JSON, but one wants to access it deserialized/decoded. In the following example, a date was encoded to its ISO 8601 representation. We use the reviver function to parse this in a JavaScript Date.
const jsonString = '{"date":"2016-01-04T23:00:00.000Z"}';
const data = JSON.parse(jsonString, (key, value) =>
key === 'date' ? new Date(value) : value
);
The reviver walks values inside-out, and it is also called for the root with the key "". If it returns undefined, or falls off the end of the function, that property is deleted. An undefined return for the root becomes the result of JSON.parse. Otherwise the property is set to the returned value.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents