3

I have JSON data in the following structure, and I'm trying to parse it in order to work with the data using javascript.

JSON Data

{
    "FirstItem": {
        "id": 1,
        "type": "foo",
        "colours": ["blue", "black", "green"],
        "reviews": {
            "positive": ["The best", "unbelievable", "Awesome"],
            "negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
            "neutral": ["OK", "Meh"]
        }
    },
    "SecondItem": {
        "id": 2,
        "type": "bar",
        "colours": ["red", "white", "yellow"],
        "reviews": {
            "positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
            "negative": ["Terrible", "Shocking", "abysmal"],
            "neutral": ["OK", "Standard", "Vanilla"]
        }
    }
}

I am trying to parse this using JSON.parse(), however this returns the following error:

JSON.parse: unexpected character at line 1 column 2 of the JSON data

I have previously worked with this same JSON structure using C#, and had to deserialise this into a dictionary - information can be found on this post

Question

How can I parse this JSON into a javascript object, which will allow me to loop and evaluate each item?

Community
  • 1
  • 1
devklick
  • 2,000
  • 3
  • 30
  • 47
  • 1
    JSON is a string. Your sample looks like a JS object. – Deblaton Jean-Philippe May 27 '18 at 17:25
  • 1
    It's already parsed... – pushkin May 27 '18 at 17:26
  • You may not need to parse it any more.just assign in to a variable and use like `variableName["FirstItem"]` – brk May 27 '18 at 17:27
  • Your right, this is already a javascript object, but how can I programmatically loop through each item? i.e. check the `FirstItem`, then check `SecondItem`, then `ThirdItem` etc... – devklick May 27 '18 at 17:31
  • For last comment see [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – charlietfl May 27 '18 at 17:43
  • Also appears that this would be better as array of objects where each object has the same property names. `[{i"id": 1, "type": "foo", "colours"...}, {"id": 2, "type": "bar", "colours":...}]` – charlietfl May 27 '18 at 17:44

2 Answers2

3

JSON is Javascript Object with double quoted key like what you have in sample. So you don't need to parse it again, see this for explanation. You can access data from it using its key or if in case you want to get reviews from SecondItem, you can access it with :

SecondItem.reviews

or

SecondItem['reviews']
Fathur Hidayat
  • 111
  • 1
  • 2
2

Apparently you are trying to parse an already parsed object

x = {A:1};       // A javascript object
JSON.parse(x);   // Error

this happens because JSON.parse will convert the object to a string first, getting "[object Object]" and then will try to parse this string.

6502
  • 112,025
  • 15
  • 165
  • 265