Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing quotation marks in JSONObject

Tags:

java

json

I'm using the net.sf.json.JSONObject to create some data to be sent to a front end application, and the code I'm interacting with doesn't like the ways its adding quotation marks to every field name.

For example:

 myString = new JSONObject().put("JSON", "Hello, World!").toString();

produces the string {"JSON": "Hello, World"}.

What I want it to return is {JSON: "Hello, World"} - without quotes around "JSON". What do I have to do to make that happen?

like image 499
Spike Williams Avatar asked Jun 01 '10 18:06

Spike Williams


People also ask

How do I remove quotes from JSON Stringify?

That makes the regex to remove the quotes from the keys MUCH easier. Start your solution with this: var cleaned = JSON. stringify(x, null, 2);

How do I pass a string with double quotes in JSON?

If you use double quotation marks, you do not need to escape single quotation marks embedded in the JSON string. However, you need to escape each double quotation mark with a backtick ` within the JSON structure, as with the following example.

How do you remove quotation marks in Python?

Call str. strip(chars) on str with the quote character '"' as chars to remove quotes from the ends of the string.


3 Answers

I've come across a few web applications/libraries such as amCharts that support JSON like JavaScipt inputs where what your requesting is necessary as true JSON is not supported.

What you can do is create a common javascript function and use a little RegEx to filter the JSON.

function CleanJSONQuotesOnKeys(json) {
    return json.replace(/"(\w+)"\s*:/g, '$1:');
}
like image 134
catalpa Avatar answered Sep 20 '22 07:09

catalpa


The javadoc says

The texts produced by the toString methods strictly conform to the JSON sysntax rules.

If you want to conform to the JSON syntax rules, you shouln't remove the quotes.

Or if you don't care about the rules, you could create you own simple method to contruct this strings.

Also, replace the 2 first occurrences of the quotes is valid, as @CharlesLeaf said.

like image 38
The Student Avatar answered Sep 22 '22 07:09

The Student


Can I ask why you want to do this? It's not going to save thát much of the total bytes being transfered in the request.

In any case, I'd say you have to write something, a regexp or something else, that replaces /\"([^"]+)\"\:/ to the first match $1. I'm not fluent in Java so I can't actually help any more.

like image 38
CharlesLeaf Avatar answered Sep 19 '22 07:09

CharlesLeaf