Javascript 使用单引号将字符串解析为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36038454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing string as JSON with single quotes?
提问by Coderaemon
I have a string
我有一个字符串
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
如何将上述字符串 (str) 解析为 JSON 对象?
This seems like a simple parsing. It's not working though.
这似乎是一个简单的解析。虽然它不起作用。
回答by ssube
The JSON standardrequires double quotes and will not accept single quotes, nor will the parser.
该JSON标准要求双引号,并且不接受单引号,也不会对解析器。
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"')
and you should end up with valid JSON.
如果您的字符串中有一个没有转义单引号的简单案例(这通常是不可能的,但这不是 JSON),您可以很简单str.replace(/'/g, '"')
,最终应该得到有效的 JSON。
回答by Min
回答by d'Artagnan Evergreen Barbosa
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
如果您确定您的 JSON 安全地在您的控制之下(而不是用户输入),那么您可以简单地评估 JSON。Eval 接受所有引用类型以及不带引号的属性名称。
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
由于 eval 解析器的工作方式,需要额外的括号。当 Eval 用于您可以控制的数据时,它并不是邪恶的。有关 JSON.parse 和 eval() 之间差异的更多信息,请参阅JSON.parse vs. eval()
回答by Vaishnavi Dongre
var str = "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);
This solved the problem for me.
这为我解决了这个问题。
回答by aup
Something like this:
像这样的东西:
var div = document.getElementById("result");
var str = "{'a':1}";
str = str.replace(/\'/g, '"');
var parsed = JSON.parse(str);
console.log(parsed);
div.innerText = parsed.a;
<div id="result"></div>
回答by Jonathan.Brink
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
JSON 中不允许对键使用单引号。您需要使用双引号。
For your use-case perhaps this would be the easiest solution:
对于您的用例,这可能是最简单的解决方案:
str = '{"a":1}';
来源:
If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.
如果属性需要引号,则必须使用双引号。所有属性名称都必须用双引号括起来。
回答by greg miller
json = ( new Function("return " + jsonString) )();