Skip to content

Produces invalid JSON #2

@Joncom

Description

@Joncom

This pretty printer currently outputs invalid JSON if the source JSON contains escaped double-quotes.

Steps to reproduce:

var json = JSON.stringify({ a: 'a', b: 'b', c: '"Hello"' });
var out = JSONFormat(json);

Expected result:

"{
	"a": "a",
	"b": "b",
	"c": "\"HELLO\""
}"

Actual result:

"{
	"a": "a",
	"b": "b",
	"c": "\1\HELLO\2\"
}"

This occurs because the double-quotes trigger a nesting situation, so when re-constructing the output, we start as usual:

"{
	\3\: \4\,
	\5\: \6\,
	\7\: \8\
}"

And this line starts re-inserting the original strings:

out = out.replace( /\\(\d+)\\/g, pop );

Running it once results in the following:

"{
	"a": "a",
	"b": "b",
	"c": "\1\HELLO\2\"
}"

But since the regex does not check for new matches introduced during the replacement, they get missed.

This can be fixed by checking for new matches in a while loop before moving on:

var pattern = /\\(\d+)\\/g;
while(pattern.test(out)) {
    out = out.replace( pattern, pop );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions