I get the json on console as
[Object]
0: Object
address: "soham"
region: "soham"
relevanceScore: "4"
startDate: "2015-05-10"
subscriptionType: "1"
verificationStatus: "1"
__proto__: Object
length: 1
__proto__: Array[0]
and my ajax call
$(document).ready(function()
{
($.ajax({
url:"allServices/getBusinessDetails.php?busid=<? echo $business_id; ?>",
dataType: "json",
success: function (jsondata) {
var allval=jsondata;
console.log(allval);
}
}));
});
but when i try to take the value out of it as allval.address it gives me undefined. How to parse the object
5 Answers 5
if you send data as json on server you can use responce.data but you can dumps json object and send it as string, and use var r = JSON.parse(responce)
Comments
I will try to explain the actual situation :
Assume you have array of objects :
var g = [{a:1,b:2},{c:1,d:2}];
Let's convert it to json string :
var json = JSON.stringify(g); //"[{"a":1,"b":2},{"c":1,"d":2}]"
Now , this is your situation :
the server returns :
"[{"a":1,"b":2},{"c":1,"d":2}]"
How can you parse it ?
var parsed = JSON.parse(json);
Great. now let's look how the browser sees it :
enter image description here
so how would you access the first item ?
Right , via [0] like dystroy write in his comment.
Comments
you can try like this
$(document).ready(function()
{
($.ajax({
url:"allServices/getBusinessDetails.php?busid=<? echo $business_id; ?>",
dataType: "json",
success: function (jsondata) {
var allval=JSON.stringify(jsondata);
console.log(allval[0].address);
}
}));
});
I'm not sure but i think its helpful to you.
2 Comments
JSON.stringify(response) and i think your response is in array that contain only one object so i am use allval[0]. you want to address from this object so i am use allval[0].address.Just use jQuery.parseJSON
like this var obj = jQuery.parseJSON( '{ "name": "John" }' );
see https://api.jquery.com/jquery.parsejson/
If you get undefined the data you are trying to parse is probebly unvalid. You can try if its valid here http://pro.jsonlint.com
Comments
$(document).ready(function(){
$.getJSON("allServices/getBusinessDetails.php?busid=<? echo $business_id; ?>",function(data){
$.each(data,function(key,value){
alert(data[key].attrib1name);
alert(data[key].attrib2name);
console.log(value);
});
});
});
Or this approach
$(document).ready(function(){
$.getJSON("allServices/getBusinessDetails.php?busid=<? echo $business_id; ?>",function(data){
parseJsonArray(data);
});
function parseJsonArray(obj) {
// Do something.
$.each(obj, function (idx, obj1) {
if (typeof obj1 == 'object') {
parseJsonArray(obj1);
} else {
alert(idx+":"+obj1);
}
});
}
allval[0].address?0. it's an arrayed json"[{},{},{}]"- hence look at dystroy's access to the array ( once it's parsed)