Reputation: 716
I want to get the id value from the following json object
answerTag:
[ '[{"id":64,"name":"Coronary Artery Disease"}]',
'[{"id":64,"name":"Coronary Artery Disease"}]' ],
risk: '1' }
Upvotes: 0
Views: 16994
Reputation: 36
I had the same issue. I found that I had to remove the leading and trailing brackets before calling JSON.parse for it to work. The JSON.parse inside a try-catch didn't fail but just the same I couldn't access the values in the resultant object.
Here's the excerpt. "rows[0]" is the the first row of my MySQL result array
result = JSON.stringify(rows[0])
result = result.replace(/(^\[)/, '');
result = result.replace(/(\]$)/, '');
try {
var resultObj = JSON.parse(result);
} catch (e) {
console.log("Error, not a valid JSON string");
}
var my_value = resultObj["my_key"];
Hope this helps!
Upvotes: 2
Reputation:
You dont have a valid JSON
as a valid json should have a key-value pair
var answerTag=
{
"key1":{"id":64,"name":"Coronary Artery Disease"},
"key2":{"id":64,"name":"Coronary Artery Disease"},
"key3":{risk: '1' }
}
So if u want to traverse that ,put it in for loop like this
getKeyValueFromJSON(answerTag);
function getKeyValueFromJSON(
for(var key in obj) {
alert("Key: " + key + " value: " + obj[key]);
}
}
Or if i am able to get it The formed JSON is like this
var obj={
answerTag: [
'[{"id":64,"name":"Coronary Artery Disease"}]',
'[{"id":64,"name":"Coronary Artery Disease"}]' ],
risk: '1'
}
So You can use it like this
for(var key in obj) {
for(var innerKey in obj[key]) {
console.log("Key: " + innerKey + " value: " + obj[key][innerKey]);
}
}
Upvotes: 1