使用单引号将字符串解析为 JSON? [英] Parsing string as JSON with single quotes?

查看:48
本文介绍了使用单引号将字符串解析为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)

如何将上述字符串 (str) 解析为 JSON 对象?

How can I parse the above string (str) into a JSON object ?

这似乎是一个简单的解析.但它不起作用.

This seems like a simple parsing. It's not working though.

推荐答案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆