0

I've got this data serialized by JSON to string:

var json = '[{"data":{"id":2,"gid":3,"name":"Travis","surname":"Stewart","skin":0}},{"data":{"id":3,"gid":3,"name":"Ziutek","surname":"Stewart","skin":0}}]';

And now im going to parse this back to object, like:

var charData = JSON.parse(json);

How can i get data from this for each datas?

for(var char in charData.data) {
console.log(char.id);
}

This wasn't work... Any other solutions?

5
  • That console log back me an errors: Error: Cannot read property 'id' of undefined Commented Apr 17, 2020 at 8:43
  • at top-level you have an array, so charData.data is wrong. You have to loop over each array item, and access the item data property ; this is not what you've done Commented Apr 17, 2020 at 8:46
  • paste your json into an inline json beautifer, such as jsonviewer.stack.hu, click on "viewer" at the top left, and see your json in a tree representation Commented Apr 17, 2020 at 8:47
  • @Pierre iv.pl/images/d01356524b8a27df9f82d9bbea968ac7.th.png - that what i've got in jsonviewer. Commented Apr 17, 2020 at 8:52
  • so you see you have to do something with the array... update your loop to handle that Commented Apr 17, 2020 at 8:53

2 Answers 2

1

Okay. Got it! Here's the code how can i get this:

var json = '[{"data":{"id":2,"gid":3,"name":"Travis","surname":"Stewart","skin":0}},{"data":{"id":3,"gid":3,"name":"Ziutek","surname":"Stewart","skin":0}}]';
var charData = JSON.parse(json);

for(var char in charData) {
console.log(charData[char].data.name);
}

Thanks a lot for all! :) SOLVED.

Sign up to request clarification or add additional context in comments.

Comments

1

you have more then one Data object , so you need to do a forOf To your chardata not to charData.data :

for(var char in charData) {
console.log(charData[char].data.id);
console.log(charData[char].data.name);
 ....
}

6 Comments

Your code put me an error in console like: Error: Cannot read property 'id' of undefined
try to log only console.log(char); and tell me what you got
That for(var char in charData) { console.log(char); } put me in console this > "0" > "1"
a screenshot please
then try : console.log(charData[char]);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.