尝试使用JavaScript将字符串转换为JSON时,出现SyntaxError:JSON解析错误:预期为'}' [英] Getting SyntaxError: JSON Parse error: Expected '}' when trying to convert a string into JSON using javascript

查看:167
本文介绍了尝试使用JavaScript将字符串转换为JSON时,出现SyntaxError:JSON解析错误:预期为'}'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

var str = "[{u'total': '54', u'value': '54', u'label': u'14 Sep'}, {u'total': '58', u'value': '4', u'label': u'15 Sep'}, {u'total': '65', u'value': '7', u'label': u'16 Sep'}]";
console.log(JSON.parse(str));

换句话说,我正在尝试使用Js将字符串转换为JSON对象列表.我相信我的字符串结构是可靠的,但是,我在控制台中收到此错误:

In other words, I am trying to convert the string into a list of JSON objects using Js. I believe my string's structure is solid, however, I get this error in my console:

SyntaxError: JSON Parse error: Expected '}'

有人可以帮我解决这个问题吗?为什么会出现此错误?

Can anyone help me fix this? Why do I get this error?

推荐答案

如果无法更改此python字典,则可以使用解决方法:

If you cannot change this python dictionary, you can use a workaround:

var str = "[{u'total': '54', u'value': '54', u'label': u'14 Sep'}, {u'total': '58', u'value': '4', u'label': u'15 Sep'}, {u'total': '65', u'value': '7', u'label': u'16 Sep'}]";

str = str.replace(/u?'(.+?)': u?'(.+?)'/g, '"$1":"$2"');

console.log(str);

console.log(JSON.parse(str));

这篇关于尝试使用JavaScript将字符串转换为JSON时,出现SyntaxError:JSON解析错误:预期为'}'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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