The result after calling JSON.parse(...) was not accurate

The following method is used in the controller:

@RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST)
  public @ResponseBody
  Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) {
    LOGGER.info("In ReportController.getChannelIntentionDetails(...), searchParameters " + searchParameters);

    return channelDetailsService.getIntentionDetails(searchParameters);
  }

Here is the structure of the Report POJO:

public class Report {

  private Map<String, Collection<String>> parameterWiseResult;
  private Collection<String>              results;
  private String                          result;
  private String                          spid;
.
.
.
}

The results collection contains JSON strings retrieved from a MongoDB collection

This snippet shows the AJAX implementation in JavaScript:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","channelIntentionDetails.html",false);
    xmlhttp.setRequestHeader("Content-Type","application/json");
    xmlhttp.setRequestHeader("Accept","application/json");
    xmlhttp.send(stringifiedSearchParameter);

    alert("Plain AJAX response "+ xmlhttp.response);
    alert("After JSON.parse(...) "+ (JSON.parse(xmlhttp.response)).results);

drawIntentionPieChart((JSON.parse(xmlhttp.response)).results);

function drawIntentionPieChart(data) {

        if (intentionGooglePieChart == null
                || intentionGooglePieChart == 'undefined') {
            intentionGooglePieChart = new google.visualization.PieChart(
                    document.getElementById('intentionPiechart'));
        }

        intentionGooglePieChart.clearChart();

        var jsonData = data;

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Intention');
        data.addColumn('number', 'Share');

        for (i = 0; i < jsonData.length; i++) {

            data.addRows([ [ jsonData[i]._id.Intention_category,
                    parseInt(jsonData[i].count) ] ]);

        }

        var options = {
            title : 'Intention Analysis',
            titleTextStyle : {
                color : '#0E5EAE'
            },
            fontSize : 14,
            width : 390,
            height : 200

        };

        intentionGooglePieChart.draw(data, options);
    }

The first alert displays the content where "results" is an array:

Plain AJAX response {"parameterWiseResult":null,"results":["{ \"_id\" : { \"SpId\" : 352 , \"Intention_category\" : \"Opine\" , \"Report_Id\" : 2 , \"Channel_Id\" : 1} , \"count\" : 1}",...],"result":null,"spid":null,"idvallistsearchprofile":null,"idvallisttags":null,"spmaster":null,"competitiveParameters":null}

The second alert strips off the array braces after JSON parsing:

After JSON.parse(...) { "_id" : { "SpId" : 352 , "Intention_category" : "Opine" , "Report_Id" : 2 , "Channel_Id" : 1} , "count" : 1},...

Subsequently, there are issues encountered while iterating over this parsed result:

TypeError: jsonData[i]._id is undefined

data.addRows([ [ jsonData[i]._id.Intention_category,
parseInt(jsonData[i].count) ] ]); 

What am I doing wrong here?

Answer №1

If you're facing an issue, worry not because there are actually 2 ways to solve it.

First Option: Adjust the format of the data returned by your service

To return a collection or array of objects from your web service, ensure that your POGO structure resembles the following:

public class Report {

    private Map<String, Collection<String>> parameterWiseResult;
    private Collection<MyObject>            results;
    private String                          result;
    private String                          spid;

    //Include appropriate Setters and Getters
}

public class MyObject {

    private Id _id;
    private int count;

    //Include necessary Setters and Getters

    private class Id {
         int SpId;
         String Intention_category;
         int Report_Id;
         int Channel_Id;

         //Implement required Setters and Getters 
    }
}

Second Option: Utilize double parsing in JavaScript to convert inner Strings to Objects. Inside a for loop, parse each element of the array into JSON as shown below:

var myJson = JSON.parse(jsonData[i]);
data.addRows([ [ myJson._id.Intention_category, parseInt(myJson.count) ] ]); 

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

Error encountered while trying to display output on screen due to Unicode encoding issues

I am currently working with a JSON file stored in S3 that includes a dynamic delimiter within the file name and the data. My goal is to eliminate these specific characters when retrieving the file from S3. Here is an example of the sample data: F ...

The main attribute in the NPM package.json is missing or has no appropriate entry

I'm really struggling to figure out the best approach for setting up my package.json file. I have a JavaScript module that contains multiple reusable JS files, let's call it Module1. In Module1's package.json, the name attribute is set to " ...

Achieve the hidden div scroll effect in React by initially hiding the div and then allowing

I am currently working on a web chat application using next.js. One of the features is an emoji picker button that, when clicked, displays a menu of emojis. The issue I am facing is that in order for the user to see the emoji menu, they have to scroll down ...

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

Having trouble accessing the POST RESPONSE json in ReactJS and NodeJS

I have set up my own API server that is connected to a MySQL database. Whenever I send a request to the server, everything seems fine. I can see the input from the browser and the output from the database in the console. However, I am unable to see any new ...

Casting types of objects in Angular2 using TypeScript

Trying to extract the model object from the JSON obtained through a http response call. The following JSON represents the body of the http response, { "dataType": "RWSupplier", "partyName": "Lifecare Pharmaceuticals", "partyShortName": null, "partySecon ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Adding a dynamic Dojo-enabled element using Zend Framework

Currently, I am developing a form using Zend_Dojo_Form. Everything is working smoothly, except when I dynamically add elements to the form (via ajax where users can click a [+] button to add more elements). Although I have successfully inserted my new Ze ...

sending JSON information to the jQuery post function

Today I'm experimenting with a jQuery code snippet: $.post("test.php", { category: "Ubuntu", newname: "Hash" }, function(data) { alert("Data Loaded: " + data); }); My goal is to include form field data in the json request. In the past, I ha ...

Is there a BindingResult present in the JavaScript response when using Spring MVC?

What is the optimal method to determine if an ajax success response controller has returned a view with validation errors? Controller: if(result.hasErrors()) { return "place/add"; } Javascript: $.ajax({ url : "<sprin ...

I am having issues with sendKeys and click() functions in my code. I am unable to access the elements using Protractor's javascript

<input class="form-control validation-field ng-dirty ng-touched ng-invalid" placeholder="Password" type="password"> Despite using the element to retrieve it, I am unable to send keys and no error message is displayed. This issue persists in both Fir ...

Learn the steps to successfully rotate the custom icon in Material-Ui select without impacting its functionality and making sure it remains clickable

I've been trying to incorporate my own icon for the material UI select component. I successfully replaced the default icon using the "IconComponent" attribute in MU select. However, I'm facing issues with the new icon not rotating when the menu ...

Exploring various results when scraping RSS feeds using the requests.get and BeautifulSoup methods

I am trying to extract data from the code found at this link: . The HTML syntax involved is "link>the URL</link' (it contains open and close <> but cannot be shown here). However, when running this code, the output for the link appears as ...

Exploring the capabilities of Angular through filter functions and ng-bind-html

I created an angular filter called 'strLimit' to restrict the number of characters in a string: mod.filter('strLimit', ['$filter', function ($filter) { return function (input, limit) { if (!input) return; if (input.le ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

to streamline the process of navigating Google Chrome web pages

Is it possible to create automation in Google Chrome that can complete the following tasks: 1. Input a job name to monitor 2. Periodically click a refresh button on the webpage (not the refresh button for the entire Chrome page in the left corner) 3. Open ...

Encountering a type conversion error when trying to parse JSON data in C

When attempting to populate a vector of json data type with json objects, I encountered an error when loading this vector into a json response. The following method was attempted to push json objects into the vector of json data type: std::vector<json_ ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

Swagger codegen static documentation with a customized moustache template specifically designed for response messages

I am utilizing swagger-codegen to create static documentation pages. The generated docs are based on Mustache templates that are part of the project. When I run the code with a sample JSON from the Wordnik Swagger API, it creates individual files for eac ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...