Jeffail/gabs

Support json path with indices

Closed this issue · 9 comments

Hi,

It would be great to have support for indices in json path's when setting a value.

E.g.
jsonObj := gabs.New() jsonObj.Set(10, "outter", "inner", "0", "value") fmt.Println(jsonObj.StringIndent("", " "))

Expected result:
{ "outter": { "inner": { "0": { "value": 10 } } } }

Proposal as patch attached
0001-Setter-index-support-added.txt

Best regards
Giovanni

Hey @giovanni-annunzio, I'd like to add this in but I'll need to add new methods rather than changing the existing ones. In the meantime you have two options:

Use JSONPointer syntax:

jsonObj.SetJSONPointer(10, "/outter/inner/0/value")

Or, use Index:

jsonObj.S("outter", "inner").Index(0).Set(10, "value")

Dear @Jeffail,

Thx for your fast response and your effort keeping the quality of this project high!

I've the requirement that I need ability to process an arbitrary path like "/outter/inner/0/value" .

Therefore only the JSONPointer solution is possible, but
jsonObj := gabs.New() jsonObj.SetJSONPointer(10, "/outter/inner/0/value")

raises: "failed to resolve JSON pointer: index '0' value 'outter' was not found"

Best regards
Giovanni

@giovanni-annunzio if it's not known that the full path of the target field exists before setting it then you'll need to do that yourself, the problem with providing a general path like foo.0.bar when constructing the path is that gabs doesn't know if 0 is an index or a key name unless the array or object already exists.

@Jeffail you are absolutely right - I didn't think this through very well.

Hi @Jeffail , I was looking for way to delete a path that traverses an array, so the json pointer workaround you proposed won't do in this case.
Either DeleteJsonPointer or jsonObj.Delete which supports array indexing will do.
What do you think about this?

Hey @itaysk, is ArrayRemove what you're after? Or is this a situation where you want to delete a value within an object within an array?

ArrayRemove assumes I know it's an array but the array could appear at any level in the path and I would like to traverse it. for now I'm using gjson which supports this

Hey @itaysk, I've updated Delete so that if the target is an array element it will work the same as when it is an object key. So for example Delete("foo", "bar", "0") will delete element 0 when bar is an array, DeleteP("foo.bar.0") does the same.

that was quick :) thanks