I know that json.stringify() function converts a json object to json string.
json.stringify({x:9})
this will return string "{"x" : 9}"
But is there a way to convert a simple string into json format? For example i want this
var str = '{x: 9}'
json.stringify(str) //"{"x" : 9}"
I know that json.stringify() function converts a json object to json string.
json.stringify({x:9})
this will return string "{"x" : 9}"
But is there a way to convert a simple string into json format? For example i want this
var str = '{x: 9}'
json.stringify(str) //"{"x" : 9}"
Share
Improve this question
asked Mar 29, 2016 at 9:36
Maira MuneerMaira Muneer
751 gold badge2 silver badges7 bronze badges
1
-
1
var str = '{"x": 9}'; var obj= JSON.parse(str)
– Rajaprabhu Aravindasamy Commented Mar 29, 2016 at 9:37
3 Answers
Reset to default 3With a proper format of string, you can use JSON.parse.
var str = '{"x" : 9}',
obj = JSON.parse(str);
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
If you are using jQuery then you can use $.parseJSON See http://api.jquery./jquery.parsejson/
Can also visit Parse JSON in JavaScript?
First solution using eval:
const parseRelaxedJSON = (str) => eval('(_ => (' + str + '))()')
JSON.stringify(parseRelaxedJSON('{x: 5}'))
(_ => (' + str + '))()
is a self-executing anonymous function. It is necessary for eval
to evaluate strings similar to {x: 5}
. This way eval
will be evaluating the expression function (_ => ({x: 5}))()
which if you're not familiar with ES6 syntax is equivalent to:
(function() {
return {x: 5}
})()
Second solution: using a proper 'relaxed' JSON parser like JSON5
JSON.stringify(JSON5.parse('{x: 2}'))
JSBin