如何在jQuery中解析这个无效的JSON字符串? [英] How do I parse this invalid JSON string in jQuery?

查看:69
本文介绍了如何在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.

这篇关于如何在jQuery中解析这个无效的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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