Jobz Jobz - 5 months ago 7
PHP Question

How to get array elements from json using javascript

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

Answer

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)

Comments