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?
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);
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.
Call str. strip(chars) on str with the quote character '"' as chars to remove quotes from the ends of the string.
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:');
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With