Generating a JavaScript JSON object by iterating through a JSP bean with the help of JSTL's c:forEach

Two Java classes are defined as follows:

public class Abc{
   private List<SomeOtherClass> someClass;
   private String k;
   private String m;
}

public class SomeOtherClass{
   private String a;
   private String b;
   private String c;

}

On a JSP page, a bean of class Abc is being created as shown below:

<jsp:useBean id="someId" class="Abc" scope="request" />

Within this JSP page and inside a script tag, a JavaScript array of JSON objects is being attempted to be created:

<script>
 var abc = (function(){
     module._myFunction = {
             "key1" :"<c:out value = '${someId.k}'/>",
             "key2" :{
                      <c:forEach varStatus='status' items='${someId.someClass}' var ="xyz">
                          "subKey1":"${xyz.a}",
                          "subKey2":${xyz.b}
                      </c:forEach>
                    }
              }
}(abc || {}))

</script>

However, there is an error of "Unexpected string" due to the code inside the c:forEach loop. Omitting subKey1 & subKey2 makes it work fine, which is expected. Is there a way to create this JSON array successfully and check abc.key2.subkey1 or abc.key2.subKey2 in the developer console?

abc.key2.subkey1 or abc.key2.subKey2 in developer console 

Answer №1

If your list contained 3 items and you wanted to expand this section of your code:

"key2" :{
    <c:forEach varStatus='status' items='${someId.someClass}' var ="xyz">
        "subKey1":"${xyz.a}",
        "subKey2":${xyz.b}
    </c:forEach>
}

it would appear as follows:

"key2" :{
        "subKey1":"a",
        "subKey2":b
        "subKey1":"1",
        "subKey2":2
        "subKey1":"y",
        "subKey2":z
}

which is not a correctly formatted json array. (Take a look at a valid JSON array example: http://www.w3schools.com/json/json_syntax.asp -- go to "JSON Arrays")

What you want it to resemble is:

"key2" :[
        {
             "subKey1":"a",
             "subKey2":"b"
        },
        {
            "subKey1":"1",
            "subKey2":"2"
        },
        {
            "subKey1":"y",
            "subKey2":"z"
        }
 ]

Therefore, you need curly braces around each element, a comma after each brace if not the last element, and the entire thing enclosed in brackets. Here is how you can achieve that:

"key2" : [
    <c:forEach varStatus='status' items='${someId.someClass}' var ="xyz">
        {
            "subKey1":"${xyz.a}",
            "subKey2":"${xyz.b}"
        }<c:if test="${!status.last}">,</c:if>
    </c:forEach>
]

Disclaimer: I have not tested this example for errors, so please let me know if you encounter any issues and I will assist you in resolving them.

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

Preserving form data using JavaScript exclusively upon submission

Hey there! I'm facing a little issue with a Form that has multiple checkboxes and a piece of JavaScript code designed to save the state of each checkbox when the user hits submit. My problem is that, currently, the checkbox state is being saved even i ...

Uploading multiple images using AngularJS and Spring framework

I'm encountering an issue with uploading multiple images using AngularJS and Spring MVC. While I can successfully retrieve all the files in AngularJS, when I attempt to upload them, no error is displayed, and the process does not reach the Spring cont ...

Android Chrome users experiencing sidebar disappearance after first toggle

Over the past few days, I've dedicated my time to developing a new project. I've been focusing on creating the HTML, CSS, and Java layout to ensure everything works seamlessly. After completing most of the work, the design looks great on desktop ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Javascript Promise: managing the flow of execution

There are a series of tasks that I need to accomplish using an API. It's crucial that these functions are executed sequentially. Each of the functions mentioned below returns a valid promise. a(analyticsConfig._listConfig) .then(function() { ...

Utilizing Jquery to create a carousel with looping functionality for flowing text

I am currently facing an issue with a carousel that contains multiple images and text. In order to make the text responsive, I have implemented a script called FlowText. The script works perfectly on the initial carousel image (the active one), but as soon ...

Tips for choosing a specific value that matches a property value within a JSON dataset

Is there a way to select a specific value in JSON based on another property value? For example, I would like to pass the configuration_code and retrieve the corresponding description. configurations: Array(2) 0: configuration_code: "SPWG" d ...

I rely on Grunt to manage my Angular 1 app, along with grunt-connect to host the website. However, when I refresh the page, there is no fallback mechanism in place, resulting in a 404 error and

Currently, I am utilizing Grunt to manage my angular 1 application and grunt-connect to serve the website. However, I have encountered an issue where on refresh, there is no fallback mechanism in place which results in a 404 error and a blank white screen. ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

Calculating the total value of individual sections using Jquery

I have multiple sections, each containing three input fields: <div class="product_quantity"> <div class="color-quantity"> <input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text"> ...

Tips for getting rid of Next.js' default loading indicator

While working on my project using Next.js, I've noticed that whenever I change the route, a default loading indicator appears in the corner of the screen. https://i.sstatic.net/FVWEU.gif Does anyone know how to remove this default loading indicator ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Experiencing the "Bad Request" error while utilizing a JSON API

Struggling with getting a json post to work in Grails, constantly receiving "bad request" errors. I've simplified everything to the point where the routine is almost nonsensical, but it remains problematic. The API should ideally respond with an erro ...

Are these two sections of my code distinctive in functionality? Do they both address potential errors in the same manner?

After receiving some helpful suggestions on my code from a user on stack overflow, I decided to revisit and make improvements. However, I am now questioning whether the changes I made handle errors in the same way as the original code. This is my initial ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Is it possible to conceal an HTML form once it has been submitted

I have a form on my website that sends the entered information to a PHP script which then emails me the details. I've implemented JavaScript form validation and jQuery Ajax to ensure the page doesn't need to be reloaded. Here is the HTML code fo ...