0

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' }
asked Jul 8, 2016 at 12:45

2 Answers 2

2

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!

answered Sep 12, 2017 at 20:33
Sign up to request clarification or add additional context in comments.

Comments

1

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]);
 } 
}
answered Nov 29, 2016 at 10:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.