-
Notifications
You must be signed in to change notification settings - Fork 169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Insert value at array indice #75
Comments
Note that I'd be willing to implement this feature if we can agree on the right implementation. |
Here's one idea. package main
import (
"fmt"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
func main() {
var a = `["a","b","c"]`
var b = `["a","b","c"]`
a2, err := sjson.SetBytes([]byte(a), "0", "d")
if err != nil {
fmt.Println(err)
}
b2, err := sjson.SetBytes([]byte(b), "1", "d")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(a2))
fmt.Println(string(b2))
// Here we'll insert a "dummy" null element
res := gjson.Get(b, "1")
if res.Index > 0 {
b = b[:res.Index] + "null," + b[res.Index:]
}
// And now it works
b2, err = sjson.SetBytes([]byte(b), "1", "d")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(b2))
}
|
Probably the less hacky way to do it would be to extract the values into a Go array then modify that array by adding the adding the new element(s) at the index. Then reserializing the array into json. This seems to effectively be the way the splice function in Javascript works. Maybe adding a splice feature to sjson or gjson would make sense. |
Thanks for your answer, and the idea. It actually isn't very different to how I'd imagined an implementation of that feature in
The "insert" behavior could be enabled using a new field in the Regarding you latter comment, this would inherently produce an allocation to hold the deserialized elements of the array, which I would avoid if I could, but that's debatable. |
Hello @tidwall,
I have a use case where I need to "insert" a value at a specific indice in an array. However, the current behavior with
SetBytes
is a replacement if a value already exist at the given indice.Consider the following example (which show the current behavior):
The output is:
Instead, I'd like to be able to insert the values, effectively shifting all the other elements of the array to the right. The output would then be:
I searched for alternatives using
sjson
orgjson
, but haven't found a way to do it with the current version of the packages.Do you have any idea to achieve that, or would you be open to add this behavior as a feature (perhaps via a path modifier) ?
Thanks
The text was updated successfully, but these errors were encountered: