tidwall / sjson

Set JSON values very quickly in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Set with empty json "-1" create an object

jeremy-carbonne opened this issue · 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

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.

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.

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