如何在jQuery中解析这个无效的JSON字符串?

问题描述:

我希望访问此数据属性中的各种数据位:

I am looking to access the various bits of data in this data attribute:

<div class="location" data="{id: 4, point: {lng: -71.413364, lat: 41.673681}, category: 'Restaurant'}">

当然,数据属性很容易在jQuery中实现。但字符串似乎是一种非标准或无效的JSON形式。我已经尝试过JSON.parse()以及分割数组的基本JS方法。从各方面来看,它似乎只是一个无效序列化的字符串。

The data attribute is easy enough to reach in jQuery, of course. But the string seems to be a non-standard or invalid form of JSON. I've tried JSON.parse() and also a basic JS method of splitting the array. By all accounts, it just seems to be an invalidly-serialized string.

我是否需要重新格式化数据字符串? (它不是来自我,它被其他惯例使用,我宁愿不打破,所以......)

Will I need to reformat the data string? (it doesn't come from me, and it's used by other routines that I'd rather not break, so...)

通常我会说这很危险(实际上我现在会说),但请尝试:

Normally I'd say this is dangerous (and in fact I'll say it now), but try:

var decoded;  eval("decoded = " + $('div.location').attr('data'));

这是无效的JSON,因为没有引用标签。

It's invalid JSON because the labels aren't quoted.