I have a function like this
data = JSON.parse(data)
where data is first, a string like this
"{\"content\":\"Hello there\",\"uid\":\"OoIEfsgabT89EJw\",\"createdAt\":1451586225268,\"user\":{\"avatar\":\"https://avatars.com/123?v=3\",\"login\":\"login\",\"name\":\"Username\",\"uid\":123}}"�
and the data transformed is now
{"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}}
when I try to access data.uid I see undefined. What am I doing wrong?
edit: the code
addItem: function(data) {
data = JSON.parse(data)
console.log("Adding: "+data)
console.log("Adding: "+data.uid)
},
edit2: the JSON was double encoded.
doing data = JSON.parse(data) two times solved, but this is completely wrong. What else can I do?
If you're using double quotes " in beginning and end that will create a string variable and not JSON, you should use it directely.
Working example:
var data = {"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}};
console.log(data.uid); //OoIEfsgabT89EJw
Not working example :
var data='{"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}}'
console.log(data.uid); //undefined
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With