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.