最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

convert a string to json object javascript - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 3

With 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

发布评论

评论列表(0)

  1. 暂无评论