user3668129
user3668129

Reputation: 4820

How to parse json with array of elements

I'm getting a json collection, which I want to parse. The data looks:

{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d17"),
    "Q" : "Q1 ?",
    "Rates" : [
            "Q1-R1",
            "Q1-R2",
            "Q1-R3",
            "Q1-R4"
    ]
}
{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d18"),
    "Q" : "Q2 ?",
    "Rates" : [
            "Q2-R1",
            "Q2-R2",
            "Q2-R3",
            "Q2-R4"
    ]
}
{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d19"),
    "Q" : "Q3 ?",
    "Rates" : [
            "Q3-R1",
            "Q3-R2",
            "Q3-R3",
            "Q3-R4"
    ]
}

I'm trying to parse with:

$.get("/getQesAns", function(data, status){
                        var obj = JSON.parse(data);

                    });

But I'm getting error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
  1. What is wrong with the object ?
  2. How can I go over the elements (there is array of docs and each doc has inner array)

Upvotes: 0

Views: 174

Answers (3)

Corey
Corey

Reputation: 5818

Although eval is considered by many to be dangerous and performance heavy, you could take this as a creative/simple solution. You could read up on the arguments on is eval is evil and proceed as you wish.

NOTE: I'm using ES2015 just for the template strings (json). As other have noted, the JSON you provided is not valid. I've added square brackets and commas assuming this is how your data actually gets returned.

var json = `[{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d17"),
    "Q" : "Q1 ?",
    "Rates" : [
            "Q1-R1",
            "Q1-R2",
            "Q1-R3",
            "Q1-R4"
    ]
},
{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d18"),
    "Q" : "Q2 ?",
    "Rates" : [
            "Q2-R1",
            "Q2-R2",
            "Q2-R3",
            "Q2-R4"
    ]
},
{
    "_id" : ObjectId("589ecc1b463ede8cf7be3d19"),
    "Q" : "Q3 ?",
    "Rates" : [
            "Q3-R1",
            "Q3-R2",
            "Q3-R3",
            "Q3-R4"
    ]
}]`;

function ObjectId(id) {
  return id;
}

var result = eval('('+json+')');

result.forEach(function(item) {
  console.log(item._id);
});

Upvotes: 0

ADyson
ADyson

Reputation: 62074

If "data" is already a valid JSON object (not a string), then you shouldn't need to run the parse method at all, you can just use it like an object straight away. But the error suggests that the data is not actually valid JSON, and your sample bears it out:

"_id" : ObjectId("589ecc1b463ede8cf7be3d17")

should probably be:

"_id" : "589ecc1b463ede8cf7be3d17"

Also, you have a list of objects at the top level, with no commas between them, and they don't seem to be part of an array either.

Depending what you're actually trying to represent, this might be a valid version:

[
  {
    "_id" : "589ecc1b463ede8cf7be3d17",
    "Q" : "Q1 ?",
    "Rates" : [
        "Q1-R1",
        "Q1-R2",
        "Q1-R3",
        "Q1-R4"
    ]
  },
  {
    "_id" : "589ecc1b463ede8cf7be3d18",
    "Q" : "Q2 ?",
    "Rates" : [
        "Q2-R1",
        "Q2-R2",
        "Q2-R3",
        "Q2-R4"
    ]
  },
  {
    "_id" : "589ecc1b463ede8cf7be3d19",
    "Q" : "Q3 ?",
    "Rates" : [
        "Q3-R1",
        "Q3-R2",
        "Q3-R3",
        "Q3-R4"
    ]
  }
]

To answer the second part of your question, you can generally iterate over the arrays using jQuery's each function:

$.each(data, function(index, obj) {
  console.log(obj._id); //just to test
  //do whatever other processing you want here

  //then to iterate over the rates for this object, just rinse and repeat:
  $.each(obj.Rates, function(index, rateObj) {
    console.log(rateObj);
    //..etc
  });
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039488

Unfortunately what you have shown is invalid JSON. This:

ObjectId("589ecc1b463ede8cf7be3d17")

Should be:

"589ecc1b463ede8cf7be3d17"

So basically you should fix your server so that it doesn't send some MongoDB internal representations but valid JSON, at least if you expect to be able to parse it with a JSON parser.

If you have no control over the server, I am afraid that the regex and string replace techniques are awaiting you to massage the string before parsing it on the client and feeding it to the JSON parser:

var massagedJSON = someSuperWizardRegexReplaceStuffThatGetsRidOfMongoDBCrap(data);
var obj = JSON.parse(massagedJSON);

Also bear in mind that you are missing comas, between the elements of the array and finally you are missing the opening [ and closing ] to make it an actual array which kind of complicates the someSuperWizardRegexReplaceStuffThatGetsRidOfMongoDBCrap function :-)

Upvotes: 1

Related Questions