Issues encountered with JSON formatting following jQuery ajax request

When my nodejs app receives data from a cordova app through a jQuery ajax call, the format is different. It looks like this:

{
     "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 format:

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

While I can easily loop through the object in the cordova app to access nested keys like objectName.network.msisdn, I face challenges doing so in my nodejs backend.

When posting the data, I use the following method:

$.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));

      }); 

My goal is to access the sub keys from the object. However, I have tried various methods such as using Json.Parse(Json.stringify(objectName)) before posting the data, removing the json dataType in the jQuery ajax call, and trying to JSON.parse( ) the object in the backend without success.

I would greatly appreciate any assistance you can provide.

Answer №1

If the format of the returned data cannot be changed, you can still access it using string notation. Below is an illustration of how string notation can be used along with a function that converts the data into a nested object for easier navigation using 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",
  "simpleKey": "simpleValue"
}

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

// The function below transforms the keys within the object
// It can be adjusted to create a new object instead
function convertKeys(data) {
  var pieces;
  for(var key in data) {
    if (data.hasOwnProperty(key)) {
      pieces = key.match(/(.+)\[(.+)]/);
      if (pieces) {
        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); // Outputs -> Ready

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

A ReactJS Error occurred: {error: 400, reason: "Failed match", message: "Failed match [400]", errorType: "Meteor.Error"}

I encountered an issue while attempting to send form data to the server when clicking on the Next Button in a Wizard Form. The error that occurs is related to an "Undefined User" warning displayed in the Console during Step 1 of the form submission: " { ...

Instructions for obtaining and storing a JSON string in a web API

Is there a straightforward method to implement POST request for saving JSON data to a local text file? I am encountering issues with getting null value when using [FromBody], and without it, the POST resource is not being found. Essentially, I want to stor ...

Using Symfony2 to send AJAX request data to a form rendering controller

I am facing an issue with a Symfony Form that I need to prefill based on the previously viewed record. The goal is to provide a way to modify the record data. I reach the form page through javascript and send an ajax request to the controller responsible f ...

MongooseError: The parameter `uri` passed to the `openUri()` function must be of type string, but instead received "undefined"

Recently delving into mongo, I encountered a connection error that has me stumped. The error message reads as follows: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

Displaying URLs stylishly with Pills Bootstrap

When a pill is selected from the list, I need to display a specific URL that can be used elsewhere. However, there is an href="#pills-something" attribute that directs to an ID below. I am looking for something like: mysite.com/myspecificpill or ...

Navigating through various product categories in Angular's routing system

Greetings! I am currently building a Shop Page in Angular 4 and encountering an obstacle with Angular routing. The issue arises when a user clicks on a product category, the intention is for the website to direct them to the shop page. On the homepage, th ...

What is the best way to execute multiple controller functions for a single route?

I have a specific route set up for users to submit loan applications. What I want to achieve is to call different controller functions based on the amount of the loan that the user is applying for. app.use('/submitLoanRequest50kMore', mw1, mw2, ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

assign a JSON key to a variable

Is there a way to use a variable as a JSON key in JavaScript? var chtid = "1234" firebase.database().ref().set ({chtid :"hi"}); In this case, chtid is the variable. I have attempted this method without success: var chtid = "1234" firebase.database().re ...

Tips for expanding AntD Table to show nested dataSource values

I need help dynamically rendering data into an antD expandable table. The data I have is a nested object with different properties - const values = [ [name = 'Josh', city = 'Sydney', pincode='10000'], [name = 'Mat ...

Encountering Error 3080: The JSON text in Custom Parse Server on Heroku and MongoLab did not begin with an array or object, and the option to allow fragments was not configured

Encountering an issue with mongoLab, Heroku, and deploying a parse server. Following the steps outlined in this blog post: After visiting Github and deploying the app to Heroku using the deploy button, I installed parse via cocoa pods and set my app keys ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

when input event occurs automatically upon returning to the page

<input type='text' class='binp'> $('.binp').on('input', function(){ alert('lorem'); }); After entering text into the .binp input field and navigating to another page, returning using the browser ...

Exploring the connection between two MongoDB collections

I currently have two collections in my MongoDB database: Category and Book Here is the category.js code: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categoryModel = new Schema({ catName: String, menuKey: String }); module.ex ...

Utilizing nested HTML within an HTML tag

Recently, I've been exploring the concept of nested HTML in Bootstrap. While following a tutorial on using Popovers, I encountered the following code; <button id="btn3" type="button" class="btn btn-primary show" ...