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'}">
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 e from me, and it's used by other routines that I'd rather not break, so...)
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'}">
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 e from me, and it's used by other routines that I'd rather not break, so...)
Share Improve this question asked May 20, 2010 at 15:35 LesterDoveLesterDove 3,0441 gold badge26 silver badges24 bronze badges 03 Answers
Reset to default 6Normally I'd say this is dangerous (and in fact I'll say it now), but try:
var decoded; eval("decoded = " + $('div.location').attr('data'));
It's invalid JSON because the labels aren't quoted.
The reason why you are getting a parse error is that the property names aren't properly quoted. This works though:
var obj = eval("(" + "{id: 4, point: {lng: -71.413364, lat: 41.673681}, category: 'Restaurant'}" + ")");
The enclosing ()
is needed to avoid eval treating {}
as a block statement.
The JSON is malformatted for parsing. It works if you reformat like this:
var obj = jQuery.parseJSON('{"id": 4, "point": {"lng": -71.413364, "lat": 41.673681}, "category": "Restaurant"}');
$("#blah").text(obj.point.lng);