javascript
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"}]'
JSON.parse(str);
LIVE DEMO
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?
Similar Posts
- Convert JSON data to String
- Prettify JSON object or array using JSON.stringify
- Convert a Number or Integer to String in Javascript
- Convert a String to Number or Integer in Javascript
- Convert a string to array using Array.from() in javascript
- Join array items and convert to string in javascript
- Editorjs blocks - JSON to HTML javascript