json icon indicating copy to clipboard operation
json copied to clipboard

`-g|--group` option is unsafe for `][` in a string

Open trentm opened this issue 11 years ago • 4 comments

$ cat foo.json
["foo"]
["bar"]

$ json -f foo.json -g
[
  "foo",
  "bar"
]

$ cat boom.json
["foo"]
["boom]["]
["bar"]

$ json -f boom.json -g
json: error: input is not JSON: Syntax error at line 2, column 1:
        ["boom]["]
        ^
["foo"]
["boom]["]
["bar"]

trentm avatar Jul 08 '13 18:07 trentm

I ran into a similar case that functions differently, which itself is surprising. I'm using v9.0.3.

@trentm's example from before works the same way as it did then:

$ cat foo.json 
["foo"]
["bar"]
$ json -f foo.json -g
[
  "foo",
  "bar"
]

and for reference:

$ json -f foo.json -ga
foo
bar

which seems surprising. But this is even more surprising:

$ cat bar.json 
[]
[]
$ json -f bar.json -g
json: error: "bar.json" is not JSON: Syntax error at line 2, column 1:
        []
        ^
[]
[]
$ json -f bar.json -ga
json: error: input is not JSON: Syntax error at line 2, column 1:
        []
        ^
[]
[]

davepacheco avatar Mar 04 '16 01:03 davepacheco

@davepacheco jsons grouping is not the best stuff in the world. The grouping of adjacent arrays (without streaming, i.e. json -g ...) is doing this content transformation:

        [/(\])\s*\n\s*(\[)/g].forEach(function (pat) {
            newBuffer = newBuffer.replace(pat, ',\n');
        });

Hence transforming:

[]
[]

to:

[,
]

which of course fails to parse. Either json does a more robust transformation here, or it could special case for empty arrays.

trentm avatar Mar 04 '16 03:03 trentm

@davepacheco Is this blocking/breaking you on something?

trentm avatar Mar 04 '16 06:03 trentm

Nope. I can work around. (Also, I didn't initially run into the syntax error with empty arrays.)

davepacheco avatar Mar 04 '16 07:03 davepacheco