无法将JSON字符串转换为Javascript对象

时间:2017-12-05 03:24:40

标签: javascript json

我正在尝试将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);

我创造了一个演示小提琴。 https://jsfiddle.net/030u9z9f/1/

似乎我的JSON格式不正确,但我不确定如何调整它。

2 个答案:

答案 0 :(得分:4)

JSON 不包含任何针对相同字符串的所有'"的键和值描述的单引号。所有Key和Value都应该被"引用,并且必须用'括起一个完整的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);

Fiddle

Ref

答案 1 :(得分:1)

尝试使用此JSON,

{
"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"
}