Manish Kumar
Manish Kumar

Reputation: 10502

Not able to read json property in javascript

I am getting this response from a API:

var ob = {"bytesSent":1087,"responseCode":200,"response":"{\"id\":\"4b1e9740-6059-11e5-9454-518e45576d76\"}","objectId":""} 

If i do ob.response.id it show undefined. What might be the trick ?

I tried var rss=JSON.parse(ob); but it show SyntaxError: Unexpected token o

Upvotes: 0

Views: 165

Answers (3)

Mitul
Mitul

Reputation: 3437

You need to change the Ob variable please check bellow code.

var ob = {"bytesSent":1087,"responseCode":200,"response":{"id":"4b1e9740-6059-11e5-9454-518e45576d76"},"objectId":""}  
alert(ob.response.id);

http://jsfiddle.net/1w5Lms5n/

Upvotes: 1

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

response is another unparsed JSON (string) inside your api response. You need to parse response:

var ob = {"bytesSent":1087,"responseCode":200,"response":"{\"id\":\"4b1e9740-6059-11e5-9454-518e45576d76\"}","objectId":""}     
var ob2 = JSON.parse(ob.response);
console.log(ob2.id);

Upvotes: 7

user2575725
user2575725

Reputation:

Problem is ob.response is JSON string and not just JSON.

var ob = {
  "bytesSent": 1087,
  "responseCode": 200,
  "response": "{\"id\":\"4b1e9740-6059-11e5-9454-518e45576d76\"}",
  "objectId": ""
};

alert(typeof ob.response);
alert(JSON.parse(ob.response).id)

Upvotes: 3

Related Questions