skip to Main Content

How do I use JSON.parse() properly in JavaScript? The current code I have should access the games object and then give an output of the games object name. Why is my code returning [object Object]?

let games = '{"games": [{"name": "Funny Game","desc": "A game to make you laugh!"}]}'
JSON.parse(games)

console.log(games[0].name);

//Should output Name

I’ve looked at Accessing json objects with no name and used to try and solve also.

2

Answers


  1. The issue here is because you call JSON.parse(), but don’t do anything with its output. You need to assign it to something, then interrogate that object to find the name property. Here’s a working example:

    let input = '{"games": [{"name": "PUBG","desc": "Original widely popularised by `The bridge incident.` PUBG is a shooter with many fun modes and distinctive gameplay.  "}]}'
    const parsedInput = JSON.parse(input)
    
    console.log(parsedInput.games[0].name);

    Note that I changed the variable names to avoid confusion between the games variable holding the JSON string and the games property holding the array of objects.

    Login or Signup to reply.
  2. Here is how you access it, there is an inner key "games"

    let games = '{"games": [{"name": "PUBG","desc": "Original widely popularised by `The bridge incident.` PUBG is a shooter with many fun modes and distinctive gameplay.  "}]}'
    let parsedJSON = JSON.parse(games)
    
    console.log(parsedJSON.games[0].name);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search