ianmin2 ianmin2 - 3 months ago 24
JSON Question

JSON format error after jQuery ajax

I'm receiving data on my nodejs app from a cordova app via a jQuery ajax call and it's formatted as

{
"network[msisdn]": "+254738XXXXXX",
"network[country]": "ke",
"network[roaming]": "false",
"network[simState]": "Ready",
"network[network]": "HSPA",
"network[simSerial]": "89254031021032011310",
"network[subscriber]": "639031023201131",
"network[service]": "GSM"
}


instead of the usual

{
network: {
"msisdn" : "",
...
}
}


I can loop through the object in the cordova phone app while accessing the nested keys like objectName.network.msisdn but I cannot once I receive the data in my nodejs backend.

I am posting the data as shown below

$.ajax({
url: 'http://'+$scope.api.host+':'+$scope.api.port+'/notices',
method: 'POST',
dataType: 'json',
data: $scope.storage.history[0]
}).then(function(response){

//! STORE THE RESULT IN THE RELEVANT OBJECT
$scope.storage.history[nextPos].locale = response;
alert(JSON.stringify(response));

});


I would like to access the sub keys from the object.

I have tried Json.Parse(Json.stringify(objectName)) before posting the data,

I have also tried to post without the json dataType in the jQuery ajax call,

I have tried to JSON.parse( ) the object in the back end all to no avail.

I really appreciate your assistance.

Answer

If you can't change how the data is returned, you can access it using string notation. Here is an example of using string notation and also a function that you could use to convert it to a nested object so that you can use dot notation.

var exampleData = {
     "network[msisdn]": "+254738XXXXXX",
      "network[country]": "ke",
      "network[roaming]": "false",
      "network[simState]": "Ready",
      "network[network]": "HSPA",
      "network[simSerial]": "89254031021032011310",
      "network[subscriber]": "639031023201131",
      "network[service]": "GSM"
}

console.log(exampleData['network[country]']); // Logs -> ke

// This converts the keys in place
// it can be modified to return a new object instead
function convertKeys(data) {
  var pieces;
  for(var key in data) {
    if (exampleData.hasOwnProperty(key)) {
      pieces = key.match(/(.+)\[(.+)]/);
      if (pieces.length > 1) {
        data[pieces[1]] = data[pieces[1]] || {};
        data[pieces[1]][pieces[2]] = data[key];
        delete data[key];
      }
    }
  }
}

convertKeys(exampleData);
console.log(exampleData);
console.log(exampleData.network.simState); // Logs -> Ready

Comments