简体   繁体   English

将字符串转换为json对象javascript

[英]convert a string to json object javascript

I know that json.stringify() function converts a json object to json string. 我知道json.stringify()函数将json对象转换为json字符串。

json.stringify({x:9})

this will return string "{"x" : 9}" 这将返回字符串"{"x" : 9}"

But is there a way to convert a simple string into json format? 但是有没有办法将简单的字符串转换为json格式? For example i want this 例如我想要这个

var str = '{x: 9}'
json.stringify(str)  //"{"x" : 9}"

With a proper format of string, you can use JSON.parse . 使用正确的字符串格式 ,可以使用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.com/jquery.parsejson/ 如果您使用的是jQuery,则可以使用$ .parseJSON参见http://api.jquery.com/jquery.parsejson/

Can also visit Parse JSON in JavaScript? 还可以使用JavaScript访问Parse JSON吗?

First solution using eval : 使用eval的第一个解决方案:

const parseRelaxedJSON = (str) => eval('(_ => (' + str + '))()')
JSON.stringify(parseRelaxedJSON('{x: 5}'))

(_ => (' + str + '))() is a self-executing anonymous function. (_ => (' + str + '))()是一个自执行的匿名函数。 It is necessary for eval to evaluate strings similar to {x: 5} . eval必须评估类似于{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: 这样, eval将对表达式函数(_ => ({x: 5}))()进行求值,如果您不熟悉ES6语法,则该等效于:

(function() {
  return {x: 5}
})()

Second solution: using a proper 'relaxed' JSON parser like JSON5 第二种解决方案:使用适当的“轻松” JSON解析器(如JSON5)

JSON.stringify(JSON5.parse('{x: 2}'))

JSBin JSBin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM