0

So i am trying to display a data from an API using JavaScript but got an undefined instead when i console.log(data) what i am getting is like below. its an object but some how its encapsulate as a string? Any idea how to covert this into a actual object i am new with JavaScript api so i am a bit confused.

 {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}  

I already tried to de serialize the data using JSON.parse(data) but no luck.

karel
  • 5,489
  • 46
  • 45
  • 50
Sarotobi
  • 707
  • 1
  • 9
  • 28

2 Answers2

3

What you have posted is actually an object with a property msg which is a strigified JSON. In order to get proper json from this try obj.msg = JSON.parse(obj.msg); Assuming obj is the response variable you can name it what you want.

See below snippet.

{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} 

const obj = {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} ;
console.log('Before parsing:' + typeof obj.msg); // string
obj.msg = JSON.parse(obj.msg);
console.log('After Parsing:' + typeof obj.msg); // object

Hope this helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
0

JSON.parse transforms a string-like-object to the object. So, it expects the whole of the object as a string. Which is not happening in your case.

You have an object key msg and its value is a string-like-object. So You need to convert the msg value to the JSON.

a couple of ways to try -

let resp = JSON.parse(data.msg)

or

return JSON.parse(data.msg)

Sarath Damaraju
  • 309
  • 2
  • 13