HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JSON conversion to single quotes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jsonconversionsinglequotes

Problem

The JSON standard uses double quotes for key names and string values, such as the following:

{"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:

{"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.