Search code snippets, questions, articles...

Convert String to JSON Data

You can use JSON.parse to convert a string to JSON data. It takes the string as a required parameter that you want to convert to JSON data.
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

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"}]'



Use callback function in JSON.parse

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
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet