patternjavascriptMinor
JSON conversion to single quotes
Viewed 0 times
jsonconversionsinglequotes
Problem
The JSON standard uses double quotes for key names and string values, such as the following:
However, the current project I am working on requires JSON-encoded objects to use single quotes instead of double quotes. (In this case
This code replaces double quotes with single quotes on key names and string values, and handles possible quote escaping issues (such as
Is this code enough to guarantee that, for any given object, a valid JSON-like string with single quotes will be generated? In other words, is there any way to break this code such that the result is not valid?
P.S: if you are interested, the reason that JSON strings must have single quotes is that I am working with Cassandra's map type, which doesn't accept double quotes.
{"one":1,"two":"two"}However, the current project I am working on requires JSON-encoded objects to use single quotes instead of double quotes. (In this case
{'one':1,'two':'two'}). Right now, there is no reasonable way to get rid of this requirement. I am using the following code to convert a JSON-encoded string from double quotes to single quotes:var encoded = JSON.stringify(...);
encoded = encoded.replace(/\\"/g, '"')
.replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
.replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
.replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");This code replaces double quotes with single quotes on key names and string values, and handles possible quote escaping issues (such as
{"\"key\"": "'value'"}, which is replaced with {'"key"', '\'value\''}).Is this code enough to guarantee that, for any given object, a valid JSON-like string with single quotes will be generated? In other words, is there any way to break this code such that the result is not valid?
P.S: if you are interested, the reason that JSON strings must have single quotes is that I am working with Cassandra's map type, which doesn't accept double quotes.
Solution
No, that code is not enough to handle any valid JSON.
Here are two examples where the result is not only different from the expected, but also unparsable:
The string:
will be converted to:
The string:
will be converted to:
Here are two examples where the result is not only different from the expected, but also unparsable:
The string:
{"hello":"wor\":ld"}will be converted to:
{'hello':'wor':ld'}The string:
{"hello":"w''orld"}will be converted to:
{'hello':'w\''orld'}Code Snippets
{"hello":"wor\":ld"}{'hello':'wor':ld'}{"hello":"w''orld"}{'hello':'w\''orld'}Context
StackExchange Code Review Q#69266, answer score: 7
Revisions (0)
No revisions yet.