admin管理员组文章数量:1388234
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
本文标签: convert a string to json object javascriptStack Overflow
版权声明:本文标题:convert a string to json object javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744507234a2609660.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论