0

I'm having trouble figuring out the correct syntax to parse this JSON output.

var text = [{"name":"bob","image":"bob.png"},{"name":"jim","image":"jim.png"}];
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].name + ", " + obj[0].image;

The expected output would be:

bob, bob.png

toblerone
  • 57
  • 7
  • 1
    The `text` is not actually `text`, but an object; don't try to `parse` something that's already an object. Just use `Object.values(text[0])` – CertainPerformance May 29 '18 at 22:15
  • `var text = JSON.stringify([{name:"bob", image:"bob.png"}, {name:"jim", image: "jim.png"}]);` ... – Martin Zeitler May 29 '18 at 22:21
  • You should be getting an error like "Uncaught SyntaxError: Unexpected token o in JSON at position 1" in your console. Searching for that yields [I keep getting "Uncaught SyntaxError: Unexpected token o"](https://stackoverflow.com/q/8081701), which will tell you what the problem is. @Ele, I think that's probably a better dupe target since the OP is not actually parsing JSON. – Heretic Monkey May 29 '18 at 22:24
  • @MikeMcCaughan yes, you're right, I wanted to address the OP to understand how the `JSON.parse` works. – Ele May 29 '18 at 22:28
  • First of all, You have to place the div ("demo") before the script, so that it exists when the script is loaded.Secondly, You have to stringify the **text** and you have to parse it. _DO not foget to place script after body tag_ `var text = [{"name":"bob","image":"bob.png"},{"name":"jim","image":"jim.png"}]; var obj = JSON.stringify(text); obj = JSON.parse(obj); document.getElementById("demo").innerHTML = obj[0].name + ", " + obj[0].image;` – xoxo May 30 '18 at 06:40

0 Answers0