Handling a JSON array error when working with a JSON string field

Attempting to create a JSONArray object with nested arrays and json strings, specifically looking at the "res" field.

[{
    "time": 123813213,
    "value": [{
        "name": "task",
        "res": "{\"taskName\" : \"NAME\", \"taskValue\" : 3}"
    }]
}]

An issue arises when returning the JSON as a String:

String jsonStr = "[{ \"time\": 123813213, \"value\": [{ \"name\": \"task\", \"res\": \"{\"taskName\", \"taskValue\"}\" }] }]";

JSONArray jsonArr = new JSONArray(jsonStr);

The problem is solved by properly escaping characters in the stored JSON string:

String jsonStr = "[{ \"time\": 123813213, \"value\": [{ \"name\": \"task\", \"res\": \"{\\\"taskName\\\", \\\"taskValue\"}\\\" }] }]";

JSONArray jsonArr = new JSONArray(jsonStr);

In the first case, remember to add extra backslashes. If the JSON string is received from an external source with only one backslash, it may cause issues.

An error is thrown in the first example:

org.json.JSONException: Expected a ',' or '}' at 61 [character 62 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
    at org.json.JSONObject.<init>(JSONObject.java:223)
    at org.json.JSONTokener.nextValue(JSONTokener.java:362)
    (...)

The second example parses correctly :

[{"time":123813213,"value":[{"res":"{\"taskName\", \"taskValue\"}","name":"task"}]}]

The goal is to make the first example return this result without errors.

Answer №1

The initial scenario should work without any issues. When extracting data from an external source, there is no need to include additional backslashes for character escaping. However, if you are manually typing out a string literal in your code, you must add backslashes to escape specific characters.

It's important to note that "{\"taskName\", \"taskValue\"}" does not represent valid JSON format. If attempted to parse, it would result in {"taskName", "taskValue"}, which is not recognized syntax in javascript. To create an array, the correct notation would be ["taskName", "taskValue"].

If the intention was to define an object, the appropriate structure would resemble

{"taskName": "Wash dishes", "taskValue": 5}

Answer №2

Could you please provide details of the exception? The JSON seems valid and should be functioning properly.

The reason why the second one is successful is due to how a JSON is converted to a String in Java, creating it in this format:

"[{\"time\":123813213,\"value\":[{\"name\":\"task\",\"res\":\"{\\"taskName\\" : \\"NAME\\", \\"taskValue\\" : 3}\"}]}]"

To confirm this, try using any JSON to String converter in Java. There doesn't appear to be anything incorrect with your JSON data.

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

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Crafting 3 intertwined combinations using the power of jQuery AJAX and PHP

Here's what I've been working on so far: The first page retrieves data and populates the first combobox, which is all good. Then, when users select a value from combo1, a second combobox is created with filtered data using AJAX - also working fin ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

Is it possible to generate grid options dynamically for various tables within AngularJS using ui-grid?

I have developed a service for ui-grid table functionality. Currently, I am able to use this service on a single page but now I want to extend its usage to multiple pages, each with different table data. How can I pass grid options and JSON data for multip ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Preventing Prepend Scroll: Tips and Tricks

Adding extra content to the top of the body can be frustrating, especially if it pushes everything down as you're trying to read. Is there a way to smoothly prepend this additional content without shifting the page layout, so that it seamlessly appear ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

The variable 'form' has not been assigned an initial value in the constructor of the property

Below is the snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-license', te ...

Typical class facing compilation issues

I have been troubleshooting my error messages but I am unable to pinpoint the issue in my code. Goal: This program is designed to allow a user to input 5 scores into an array. It will then sort the data in descending order and calculate the mean for the ...

What is the best way to incorporate the {id} property into my Next.js dynamic route using the Context API?

I am encountering an issue with passing the ${id} property to my dynamic route [id]>page.jsx, located within the CartItemPage.jsx file. The setup involves using the Context API, similar to React, where I maintain an array of CartItems to render the Cart ...

What strategies can be utilized to raise the max-height from the bottom to the top?

I am facing the following coding challenge: <div id = "parent"> <div id = "button"></div> </div> There is also a dynamically generated <div id="list"></div> I have successfully implem ...

Marker on Google Maps in Dark Mode is not displaying properly

I have integrated a custom map into my website using the npm module called google-map-react. The provided tutorial demonstrates how to implement a basic marker on the map, and you can find it here: . Here is an example of what it should look like: import ...

Ways to retrieve the value of a concealed element without any activation signal

In my project, I've created a slider that dynamically shows different forms one by one. Each form contains a hidden element with a specific value that I need to retrieve (using its class) every time a new form is displayed. This way, I can use that el ...

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

Insert title into PDF document

I am currently working on a react application that generates PDF documents easily. The libraries I have utilized are: jspdf html2canvas Below is the code snippet that demonstrates my approach: index.js: <div className="App"> < ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...