devklick
devklick

Reputation: 2629

Json to javascript dictionary

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?

Upvotes: 3

Views: 3443

Answers (2)

Fathur Hidayat
Fathur Hidayat

Reputation: 111

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']

Upvotes: 3

6502
6502

Reputation: 114481

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.

Upvotes: 2

Related Questions