Reputation: 6092
I am accessing a key from json object but it returns undefined
{"body":"Hi","date":"2016-07-29 07:43:00"}
var a = JSON.parse(JSON.stringify(r.txt));
console.log(a.body)
//undefined
value of r is
{
username: '1',
txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}',
}
I have tried using stringify and then parse to json but still return undefined.
Upvotes: 5
Views: 11103
Reputation: 115262
In your code stringified result would be "\"{\"body\":\"Hi\",\"date\":\"2016-07-29 07:43:00\"}\""
(which is valid string representation in JSON), parsing it would again provide the string as result not the object. When you were trying to get body
property of string which will be undefined
since there is no property like body
for a string.
So there is no need to stringify a JSON string again just avoiding the stringify method would make it work.
var r = {
username: '1',
txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}',
};
// parse the JSON string and get the object
var a = JSON.parse(r.txt);
console.log(a.body)
Upvotes: 3
Reputation: 183
You have to remove single quote in r.txt and it should work
Here is the code I updated :
var r = {
username: '1',
txt: {"body":"Hi","date":"2016-07-29 07:43:00"},
};
var a = JSON.parse(JSON.stringify(r.txt));
console.log(a.body)
If r.txt
is string
you only need parse it. If it's an object
, you will convert it to string by stringify
then parse
it
Upvotes: 1
Reputation: 66
You've to parse your json
like this. Ensure that your whatever input you're giving to JSON.parse, it should be a string.
You can run the below snippet to ensure that it's working and giving output Hi
.
var json = '{"body":"Hi","date":"2016-07-29 07:43:00"}';
var a = JSON.parse(json);
document.write(a.body);
Upvotes: 5