Issue while converting HTML to JSON
I have a div which contains this:
<div id="hidLocsJsonForAutoComplete" style="display:none;">[{"id":1,"desc":"Amazon","name":"amazon"},{"id":2,"desc":"Apple Bees","name":"applebees"},{"id":3,"desc":"Babys r Us","name":"babysrus"},{"id开发者_如何转开发":4,"desc":"Costco","name":"costco"},{"id":5,"desc":"Concord Produce","name":"concordproduce"},{"id":6,"desc":"Grocery Outlet","name":"groceryoutlet"},{"id":7,"desc":"New India Bazar","name":"newindiabazar"},{"id":8,"desc":"SubWay","name":"subway"},{"id":9,"desc":"Walmart","name":"walmart"}]</div>
and then in the script section I have this
var jsonLocs = $('#hidLocsJsonForAutoComplete').html();
Now, jsonLocs[0] is returning
[
instead of
{"id":1,"desc":"Amazon","name":"amazon"}
I understand jsonLocs is considered as string. But how do I get the the first Json object in this array ?
jsonLocs contains a String object you need to parse the inner HTML as json. Try this:
var jsonLocs = $.parseJSON($('#hidLocsJsonForAutoComplete').html());
If you are using jQuery 1.4.1 or newer, you can use jQuery's inbuilt .parseJSON()
function:
var jsonLocs = $.parseJSON($('#hidLocsJsonForAutoComplete').html());
On older versions, you can just use eval (and expose yourself to potential security/etc issues by doing it wrong, but..):
var jsonLocs = eval('('+$('#hidLocsJsonForAutoComplete').html()+')');
Never Mind, got the answer !! :)
var jsonLocs = eval($('#hidLocsJsonForAutoComplete').html());
Did the magic. But wondering if this is the most effecient/recommended way to do this.
The variable jsonLocs
is just a string, that's why when you index the first element, you're getting the first character of the string. What you need to do is parse the value of the HTML into a Javascript object, and then take the first element.
So, you will then need to do something like this:
var jsonLocs = JSON.parse($('#hidLocsJsonForAutoComplete').html());
And of course, for browsers that do not support native JSON parsing, you can use Douglas Crockford's wonderful library (or use eval
if you like to live dangerously).
精彩评论