Ways to retrieve various JSON arrays in Javascript

I have a Java servlet that constructs JSON objects and arrays and sends them as a response. After sending the initial JSON data, I then loop through a list to create more JSON objects.

JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("Status", status);
jsonObject.put("isActive", isActive);

jsonArray.add(jsonObject);
response.getWriter().write(jsonArray.toString());

// Additional for loops are executed here.

JSONArray jsonArray2 = new JSONArray();
for(int i=0;i<list.size();i++){
DTO dtost = list.get(i);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Label",dtost.getLabel());
jsonObj.put("UNID",dtost.getUNID());

jsonArray2.add(jsonObj); 
}

response.getWriter().write(jsonArray2.toString());

However, I am facing challenges in formatting this JSON correctly and accessing its values using JavaScript.

[{"Status":"Passed","isActive":"No"}] [{"Label":"MembershipCard","UNID":"01"},{"Label":"LoyaltyCard","UNID":"02"}]

In my attempt to retrieve the JSON values with JavaScript, I am not successful:

success: function(data) {

  alert(data[0].Status); // This returns nothing
}

If you have any insights on how to properly format and access this JSON data in JavaScript, I would greatly appreciate it.

Answer №1

The JSON mentioned above is considered invalid. However, if we make a modification to the JSON like this "[[{"State":"Passed","isAvailable":"No"}], [{"Category":"MembershipCard","ID":"01"},{"Category":"LoyaltyCard","ID":"02"}]]" then it would become a valid JSON.

To retrieve the State parameter from the data provided above, you can do something similar to this:

success: function(data){<br>
    alert(data[0][0].State);<br>
}

Answer №2

To optimize your Java code for generating a valid JSON object, follow these steps:

JSONObject output= new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();

// Add data to the first array
jsonObject.put("Status", status);
jsonObject.put("isActive", isActive);
jsonArray.add(jsonObject);
output.put("first", jsonArray);

// Use for loops to populate the second array
JSONArray jsonArray2 = new JSONArray();
for(int i=0; i<list.size(); i++){
    DTO dtost = list.get(i);
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("Label", dtost.getLabel());
    jsonObj.put("UNID", dtost.getUNID());

    jsonArray2.add(jsonObj); 
}
output.put("second", jsonArray2);

response.getWriter().write(output.toString());

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

When a user deletes a Web Page element from their Browser, is there an event that is triggered?

One method I have used to bypass restrictions on poorly written websites is manually deleting webpage HTML elements. To maintain security and keep intruders at bay without disrupting user experience, I am exploring options to implement automatic logout aft ...

Having trouble with the autocomplete feature on your textbox in CodeIgniter?

controller: Welcome.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { function __construct() { parent :: __construct(); $this->load->helper ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

How to properly serialize a custom authentication backend in Django

My Django 1.10 application has a custom authentication backend. When I try to log in, the error message TypeError: <class 'CustomAuthBackend'> is not JSON serializable appears. To bypass this issue, I added SESSION_SERIALIZER='django.c ...

Adding JSON data into a MongoDB database

Currently, I am working with a JSON Object that is being generated using the Gson Library in Java. My aim is to store this object in MongoDB utilizing the Java Mongo Driver v3.8.1. I specifically want to use UUIDs as ids and int64 data type for my Integers ...

Issues encountered - nodejs-lts (exit code 1603) - Problem occurred during execution of 'C:ProgramDatachocolateylib odejs-lts oolschocolateyinstall.ps1' script

Encountering Issues with Installing 64-bit Version of nodejs-lts... Received a Generic MSI Error during installation, indicating a local environment issue rather than a problem with the package or MSI file itself. Possible reasons for thi ...

From Ruby to Javascript: Solving the Challenges of Date Calculation

Can you help me convert this Ruby snippet into JavaScript? I can't seem to get the expected output. Here is the original Ruby code: require 'date' moment = DateTime.new(2014, 9, 27, 0, 0, 0, DateTime.now.offset) intervals = [['day&apo ...

Unexpected JSON parsing issue encountered in my Node.js hubot script

When looking at the message in robot.hear, I am breaking it down: robot.hear /^\[(.+)\]$/, (res) -> json_string = res.match["input"] try params = JSON.parse json_string console.log "success" catch error console.log "error" ...

Combining text objects in JQ using groupby and concatenation

I am struggling to merge multiple entries when producing multiple lines. My goal is to convert the given Source JSON into a CSV format as shown below: Source JSON: [{"State": "NewYork","Drivers": [ {"Car": "Jetta","Users": [{"Name": "Steve","Details": {"L ...

Issue with Discord.js: Newly joined user's username appears as undefined

robot.on('guildmateEntry', person =>{ const greeting = new Discord.MessageEmbed() .setTitle(`Greetings to the realm, ${individual}!`) const room = person.guild.channels.cache.find(channel => channel.name === " ...

What is the delay on iOS between touchstart and touchmove events?

Currently, I am in the process of adapting my web application for mobile device use. One of my main goals is to incorporate support for touch gestures, such as horizontal scrolling. However, I have encountered some unexpected behavior while working on this ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

Transform time-consuming tasks into asynchronous operations

How can a time-consuming function, like image manipulation, be executed asynchronously to enable other code to run simultaneously or to allow multiple instances of the same function to run in parallel? (specifically in Node.js) One example could be using ...

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

JSON-generated Personalized Listview

I am facing an issue with displaying 2 pieces of data in one row of a ListView. The problem lies within the showList() method. I am unable to utilize my custom ListView XML to show both the item and itemsemail arrays, as it only displays one data. My goal ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Divergence between two distinctive occurrences in Google Analytics

Why are there differences in the number of unique events recorded by Google Analytics for two consecutive events? I have set up onClick tracking for a button. When the button is clicked, an event (Event 1) is sent to Google Analytics and a CSS-selector ap ...

Using a pointer to reference an array of integers and calculating the sum

After being tasked with creating a function Adder() that takes in a pointer to an integer array and returns the sum of its elements, I successfully wrote the code: #include <bits/stdc++.h> using namespace std; int Adder (int *ptr) { int sum ...

Creating a Bash script that appends a new element to a JSON array

I am working with a JSON file that looks like this: { "id": 123, "guid": "XXXX", "isEnabled": true, "createdBy": "Admin", "updatedBy": "XXXXX", "createTime&quo ...