Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot use dot notation on JSON

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?

like image 630
Luiz E. Avatar asked Jul 21 '26 02:07

Luiz E.


1 Answers

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.

like image 104
Zakaria Acharki Avatar answered Jul 22 '26 14:07

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!