sjson icon indicating copy to clipboard operation
sjson copied to clipboard

Feature request - allow sets via array accessors

Open codingconcepts opened this issue 7 years ago • 7 comments

It'd be really handy to be able to set fields using the following array syntax in the same way gjson allows for gets via the syntax:

body := `{
	"people": [
		{ "id": 1, "name": "alice" },
		{ "id": 2, "name": "bob" }
	]
}`

body, err := sjson.Set(body, `people.#[id="1"].name`, "carol")
if err != nil {
	log.Fatal(err)
}

fmt.Println(body)

Is this something that could be added to the library?

codingconcepts avatar Jan 22 '18 19:01 codingconcepts

I'm here for similar. Would like to be able to use wildcard * for setting (it could set all matches, but I'd anticipate only one).

TomAnthony avatar Jul 06 '18 08:07 TomAnthony

I agree that this would make for a very good enhancement. Unfortunately my schedule Is pretty backed up and it may take sometime before I can get to this feature, but I would be happy to get some help.

tidwall avatar Jul 11 '18 05:07 tidwall

+1. Needs that

Or gjson adds something like path = gjson.GetPath(xx, searchpattern) which would be used in sjson.Set(xx, path, ..)

qinst64 avatar Jul 26 '18 09:07 qinst64

+1

Thanks for creating and sharing sjson and gjson @tidwall. They are really useful libraries.

However, I've also hit a bit of a stumbling block because sjson doesn't support the same path syntax as gjson such as people.#.name or people.#[id=1].name as mentioned by @codingconcepts.

Alternatively, the suggestion by @qinst64 would help me too but perhaps the path could be a member of the gjson Result struct. This would mean when you use result.Array() on the result of people.#[id=%].name, you'd get the paths of each result, i.e. people.0.name and people.1.name

thirstycoda avatar Oct 03 '18 23:10 thirstycoda

Just started using libraries and found out that sjson doesn't support the same path syntax as gjson. Is there a way at least to get an array index number from gjson result?

gen2brain avatar May 19 '19 15:05 gen2brain

jeremy-carbonne - are you planning to submit a PR?

itaysk avatar Sep 27 '19 07:09 itaysk

i've also bumped into the sjson limitation with setting array elements. note it seems to work when the wildcard is at the leaf (e.g.: value[*]) but not when otherwise.

it also seems inconsistent with gjson which supports the wildcard.

p.s. @tidwall , if this is simple enough to explain & you have the solution in your head, please share it - it will make it easier for anyone who finds some time & has enough justification :)

eitanb avatar Jul 04 '20 10:07 eitanb