sjson icon indicating copy to clipboard operation
sjson copied to clipboard

Set with empty json "-1" create an object

Open jeremy-carbonne opened this issue 5 years ago • 4 comments

Hi,

I tried to do:

sjson.Set("", "-1", "bob")

I expecting ["bob"] but i got {"-1":"bob"}

I think sjson.Set("", ":-1", "bob") should return {"-1":"bob"} and sjson.Set("", "-1", "bob") should return ["bob"]

Example: https://play.golang.org/p/SVqFuZs0DXh

jeremy-carbonne avatar Aug 07 '19 11:08 jeremy-carbonne

I was also wondering if this is the proper behavior or a bug. I was also expecting that -1 will create an array and not a map.

julioSab avatar Aug 22 '19 13:08 julioSab

Right now that is proper behavior. A -1 is treated as an object key when the parent does not exist. Only when the parent is an existing array will it append the value.

For example, sjson.Set("[]", "-1", "bob") results in ["bob"]. But, sjson.Set("", "-1", "bob") results in {"-1":"bob"}. Just as sjson.Set("{}", "-1", "bob") results in {"-1":"bob"}.

I can see how this is a problem though. It would be super nice to just use -1 to append to an array and/or automatically create the array if it doesn't exist . Beside, -1 would be a very strange object key.

I don't have a problem with making this change.

tidwall avatar Aug 22 '19 23:08 tidwall

as mentioned, use sjson.Set("[]", "-1", "bob"). validating what kind of data/json you are manipulating should be your code's concern.

ghost avatar Sep 05 '19 15:09 ghost

@jeremy-carbonne will you submit your work? https://github.com/jeremy-carbonne/sjson/tree/minus_one

zzzuzik avatar Nov 22 '19 02:11 zzzuzik