Logo


Json Parse in Javascript


To decode a JSON-string, we need another method named JSON.parse
For instance:


1
2  let numbers="[0,1,2,3]"; 
3  numbers=JSON.parse(numbers)
4  alert(numbers[1])
5

Or for nested objects


1let userData = '{ "name": "John", "age": 35, "isAdmin": false, "friends": [0,1,2,3] }';
2  let user = JSON.parse(userData);
3  alert( user.friends[1] )

Reviver


Optional function(key,value) that will be called for each (key, value) pair and can transform the value

Using Reviver

Imagine, we got a stringified meetup object from the server. It looks like this:
And now we need to deserialize it, to turn back into JavaScript object. Let’s do it by calling JSON.parse Let’s pass to JSON.parse the reviving function as the second argument, that returns all values “as is”, but date will become a Date :


1let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
2  let meetup = JSON.parse(str, function(key, value) {
3  if (key == 'date') return new Date(value);
4  return value;
5  });
6     alert( meetup.date.getDate() );

1 let schedule = {
2        "meetups": [
3        {"title":"Conference","date":"2017-11-30T12:00:00.000Z"},
4        {"title":"Birthday","date":"2017-04-18T12:00:00.000Z"}
5        ]
6        };
7        schedule = JSON.parse(schedule, function(key, value) {
8            if (key == 'date') return new Date(value);
9            return value;
10            });
11            alert( schedule.meetups[1].date.getDate() ); 
12        


About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share