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?

6
  • 1
    JSON is a string. Your sample looks like a JS object. Commented May 27, 2018 at 17:25
  • 1
    It's already parsed... Commented May 27, 2018 at 17:26
  • You may not need to parse it any more.just assign in to a variable and use like variableName["FirstItem"] Commented May 27, 2018 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... Commented May 27, 2018 at 17:31
  • For last comment see Access / process (nested) objects, arrays or JSON Commented May 27, 2018 at 17:43

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.