I am trying to extract an array from my json string. Please help me. I have the following javascript code,
function lookup(inputString,autoSuggestionsList,TextFieldName)
{
autoSuggestionsListMain=autoSuggestionsList;
inputTextField=TextFieldName;
if(inputString.length == 0)
{
$('#suggestions').hide();
}
else
{
$.post("show_location_hint.php",
{ queryString: ""+inputString+"" },
function(data) { if(data.length >0) { } });
}
}
my show_location_hint.php file will echo the following json string
{"root": {"success":"1","message":"","data":{"locations":[a,b,c]}}}
how can I get the elements from the array locations? please help me Thanks
You can parse it to an array using JSON.parse()
:
var dataArray = JSON.parse(jsonString)
Then just simply do stuff like:
alert(dataArray.root.message)
Try this:
$.post("show_location_hint.php", { queryString: inputString }, function(data) {
if (data) {
var locations = data.root.data.locations;
}
});
Note however that your JSON format is not valid as, a
, b
, and c
should be wrapped in double quotes. I'm guessing this is just a sample of your actual data though.
First your json is well formed. It should be:
{"root": {"success":"1","message":"","data":{"locations":["a","b","c"]}}}
and you can get data like this using jQuery:
var data = {"root": {"success":"1","message":"","data":{"locations":["a","b","c"]}}};
console.log(data.root);
console.log(data.root.success);
console.log(data.root.data);
$.each(data.root.data,function(index,item){
console.log(item);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.