javascriptjsonmongodbmeteor

Javascript Json Parser


I am trying to write a JSON parser using only javascript. The reason I only want to use javascript is that I want to parse the result returned from an API on server side in Meteor. However, I am having trouble parsing it. Below is the JSON returned:

{
   "R_5N4205x1hhF6pGZ":{
      "ResponseSet":"Default Response Set",
      "Name":"Anonymous",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "Status":"16",
      "StartDate":"2014-01-09 11:19:51",
      "EndDate":"2014-01-09 11:19:56",
      "Finished":"1",
      "Q1":"Hello "
   },
   "R_7mqYPn4rZfNtVif":{
      "ResponseSet":"Default Response Set",
      "Name":"Anonymous",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "Status":"16",
      "StartDate":"2014-01-09 11:21:58",
      "EndDate":"2014-01-09 11:22:05",
      "Finished":"1",
      "Q1":"Name identifier"
   },
   "R_bHs2h06HSQ1h2Qh":{
      "ResponseSet":"Default Response Set",
      "Name":"Anonymous",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "Status":"16",
      "StartDate":"2014-01-09 11:28:24",
      "EndDate":"2014-01-09 11:28:30",
      "Finished":"1",
      "Q1":"Test"
   },
   "R_20rlmxxgGkYnWWF":{
      "ResponseSet":"Default Response Set",
      "Name":"Some, Name",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "Status":"0",
      "StartDate":"2014-01-09 12:21:15",
      "EndDate":"2014-01-09 12:21:27",
      "Finished":"1",
      "Q1":"hjjhhjhj"
   },
   "R_e36yuRbnMmh38dD":{
      "ResponseSet":"Default Response Set",
      "Name":"Anonymous",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "IPAddress":"161.185.153.4",
      "Status":"0",
      "StartDate":"2014-01-09 12:23:04",
      "EndDate":"2014-01-09 12:23:11",
      "Finished":"1",
      "Q1":"hello world "
   }
}

I want to save each response object with an object parent key as key "responseID": value (i.e array["responseID"]="R_e36yuRbnMmh38dD")

  "R_e36yuRbnMmh38dD":{
      "ResponseSet":"Default Response Set",
      "Name":"Anonymous",
      "ExternalDataReference":"",
      "EmailAddress":"",
      "IPAddress":"161.185.153.4",
      "Status":"0",
      "StartDate":"2014-01-09 12:23:04",
      "EndDate":"2014-01-09 12:23:11",
      "Finished":"1",
      "Q1":"hello world "
   }

I want to save the resulting set in mongoDb.


Solution

  • You can use NodeJS JSON.parse() function but if I understand you want more create an object with the key in the object.

    here is the code, if it is what you want to do :

    var originalObject;
    var resultArray;
    for (var key in originalObject) {
       if(originalObject.hasOwnProperty(key )){
         var obj = originalObject[key];
         obj.responseID = key;
         resultArray.push(obj);
       }
    }
    

    But your question is a bit confusing. for mongoDB, I suggest the nodejs native driver