JSON.parse ()
An everyday use of JSON to exchange data to/from a web server.
When you receive data from a web server, the data remains wireless.
Combine data with JSON.parse (), and data becomes a JavaScript object.
Example - Dividing JSON
Suppose we received this text from a web server:
'{"name": "John", "age": 30, "city": "New York"}'
Use the JavaScript function JSON.parse () to convert text into JavaScript:
const obj = JSON.parse ('{"name": "John", "age": 30, "city": "New York"}');
Ensure the text is in JSON format; otherwise, you will get a syntax error.
Use the JavaScript object on your page:
For exampleWhen you use JSON, parse () in JSON available from the same members, the method will return the JavaScript list instead of the JavaScript object.
For example
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse (text);
The opposite
Divorce dates
Date items not allowed in JSON.
Write it as a character unit if you need to enter a date.
You can change it back to an item of the day later:
For example
Convert thread to date:
const text = '{"name": "John", "birth": "1986-12-14", "city": "New York"}';
const obj = JSON.parse (text);
birth = new day (birthday);
document.getElementById ("demo") .HTML internal = obj.name + "," + obj.birth;
Or, you can use the second parameter of the JSON.parse () function, called reviver.
Recovery parameter for testing each asset before returning a value.
For example
Convert thread to date, using reviver function:
const text = '{"name": "John", "birth": "1986-12-14", "city": "New York"}';
const obj = JSON.parse (text, function (key, value) {
if (key == "birth") {
return new date (value);
} more {
return value;
}
});
document.getElementById ("demo") .HTML internal = obj.name + "," + obj.birth;
Tasks are not allowed in JSON.
If you need to enter a function, write it as a character unit.
You can turn it back on for later:
For example
Toggle wiring:
const text = '{"name": "John", "age": "function () {return 30;}", "city": "New York"}';
const obj = JSON.parse (text);
obj.age = eval ("(" ("+ obj.age +") ");
document.getElementById ("demo"). Internal HTML = obj.name + "," + obj.age ();