Skip to content
Sign upLog in
← Back to Community
JSON parsing is not working
Profile icon
DabDatBass

So, I'm making a "shop" and the code in script.js shows how I'm going to be saving data, and I have some JSON in the third item of the array for storing the user's shopping cart, though when I want it to get the price of cattabby in the JSON, it gets "undefined". Any help?

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
DabDatBass
Comments
hotnewtop
Profile icon
Coder100

Arrays start at index 0. You tried to access the fourth item, which is a boolean lol

Correct code:

var saver = ["password", "email", '{"cattabby": 340, "plasma4ku75intv": 8500, "hpss": 16.50}', false] var json = saver[2]; var objCart = JSON.parse(JSON.stringify(json)); document.write(objCart.cattabby);
Profile icon
DabDatBass

Didn't work :/

@Coder100

Profile icon
Coder100

You stringified it so it became a string silly

@DabDatBass

Profile icon
Coder100

Just parse it directly

@DabDatBass

Profile icon
RYANTADIPARTHI

The reason it is undefined is because it cannot happen. You can't do that. But if you are stringifying that, it probably will though. Stringing it.

Profile icon
realTronsi

You cannot JSON parse an array. If you try stringifying, you will see, as the name suggests, turns it into a string. Parsing will do the opposite, turn a string back to its original form.

Profile icon
realTronsi

@realTronsi
could you also explain why you're trying to parse it? Doesn't make sense to me