JSON.parse()
its used to convert text into a JavaScript object
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
We can check what type is currently here.
using typeof() we can find the type
Ex:
var str='{"name":"John", "age":30, "city":"New York"}';
alert(typeof(str));its shows string
after converting text into oject
var o=JSON.parse(str);
alert(typeof(str));now its shows object
For example
if we receive data like this
'{"name":"John", "age":30, "city":"New York"}'
Now we convert text into object
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Make sure the text is in JSON format, or else you will get a syntax error.
Parsing Dates
Date objects are not allowed in JSON.
If you need to include a date, write it as a string.
You can convert it back into a date object later.
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
Parsing Functions
Functions are not allowed in JSON.
If you need to include a function, write it as a string.
You can convert it back into a function later.
Convert a string into a function:
const text = '{"name":"John", "age":"function () {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.