我正在尝试将 JSON 字符串转换为 javascript 对象,但没有成功。
这是我的代码:
result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);
我创建了一个带有演示的 fiddle 。 https://jsfiddle.net/030u9z9f/1/
看来我的 JSON 格式不正确,但我不确定如何调整它。
最佳答案
JSON 不包含键和值描述的任何单引号,您已将同一字符串的所有 '
更改为 "
。那里所有的键和值都应该用"
引用,并且完整的JSON字符串必须用'
括起来,以便更好地进行字符串转换。
JSON 标准需要双引号,不接受单引号,解析器也不接受。
如果你有一个简单的情况,在你的字符串中没有转义单引号(这通常是不可能的,但这不是 JSON),你可以简单的 str.replace(/'/g, '"') 然后你应该以有效的 JSON 结尾。 检查...
result = '{"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg", "sender": "Test test123", "text": "Test 005", "expiry": "2016-10-15 01:51:28", "points": 650, "color_from": "#8DBCC5", "color_to": "#13717C"}';
result = JSON.parse(result);
console.log(result);
alert(result);
关于javascript - 无法将 JSON 字符串转换为 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47645574/