const str_data = '{"name": "Rick Grimes", "city": "New York","pincode": "000-000"}';
//Parse to json data
const json_data = JSON.parse(str_data);
//Using callback function in JSON.parse
const json_data2 = JSON.parse(str_data, function(key, value) {
//DO something here
})
JSON.parse() method is used to convert a JSON data string to JSON data and use it for further operations like loop through objects and arrays.
A simple example is to convert a string to JSON data using JSON.parse.
const str = '[{"id":1,"name":"Carol"},{"id":2,"name":"Darayl"}]'
JSON.parse(str);
LIVE DEMO
You can pass a callback function in JSON.parse and apply some conditions if you want to return some other values. A simple example for using the callback function is as below.
var data = '[{ "id": 1, "name": "Math" },{ "id": 2, "name": "Physics" },{ "id": 3, "name": "Chemistry" }]';
var json = JSON.parse(data, function(key, value) {
//Do something here
});
0 Comments