Posted on: October 31, 2022|1 min read|Amrish Kushwaha

JSON: Transform data with help of reviver

JSON: Transform data with help of reviver

What is JSON?

The full form of JSON is Javascript Object Notation. JSON is plain text written in Javascript object notation. It is used to send data across networks/computers. The structure of the JSON string looks similar to Javascript Object, That’s why it is very easy to have the conversion between these two (JSON vs Javascript Object).

JSON is language agnostic.

As a javascript developer, you might have to deal with JSON as well in your day to day life.

You may have seen JSON string similiar to this:

'{ "hello": "world"}'

The above code is very simple example of JSON string.


Javascript supports these methods to deal with JSON.

  1. JSON.stringify() → To convert the javascript object to JSON string.
  2. JSON.parse() → To convert JSON string to the javascript object.

In this article, I will discuss the parse method of JSON.

JSON parse

The parse method is used to convert JSON strings to the respective Javascript object.

const jsonString = '{"hello": "world"}' const obj = JSON.parse(jsonString) console.log(obj) // { hello: "world" }

Syntax of parse method

JSON.parse(jsonString, reviver) // here reviver is optional // Syntax for reviver // function reviver(key, value) { }

Here reviver is a function which takes key and value as parameters. The reviver's job is to transform data before it will be returned. The reviver function will return value.

Use reviver to transform data:

The reviver is the function which is used to transform the data before returning it.

If the reviver returns undefined (or returns no value - for example, if execution falls off the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value.

If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.

Example:

JSON.parse('{"greeting": "hello"}', (key, value) => typeof value === "string" ? `${value} world` : value ) // { greeting: "hello world" }

Thanks for reading the article. Keep coding and keep solving problems.

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Frontendroom
© 2023 · Copyright Frontendroom