使用单引号将字符串解析为JSON? [英] Parsing string as JSON with single quotes?
本文介绍了使用单引号将字符串解析为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
我如何在上面解析字符串(str)到JSON?这看起来像一个简单的解析;它不能以某种方式工作。
How can I parse above string (str) to JSON ? This seems like a simple parsing; it's not working somehow.
推荐答案
JSON标准需要双引号,不接受单引号,解析器也不接受。
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
如果你有一个没有转义单引号的简单案例在你的字符串中(这通常是不可能的,但这不是JSON),你可以简单的 str.replace(/'/ g,'')
你应该最终得到有效的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文