Skip to content

Instantly share code, notes, and snippets.

@tidwall
Created February 9, 2017 20:00
Show Gist options
  • Save tidwall/6721ca049e71252f2bbe0c6ed1c9c575 to your computer and use it in GitHub Desktop.
Save tidwall/6721ca049e71252f2bbe0c6ed1c9c575 to your computer and use it in GitHub Desktop.
Delete multiple items with S|GJSON
package main
import (
"fmt"
"log"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
var json = []byte(`
{
"name": {"first": "Tom", "last": "Anderson"},
"age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "Dale", "last": "Murphy", "age": 44},
{"first": "Roger", "last": "Craig", "age": 68},
{"first": "Jane", "last": "Murphy", "age": 47}
]
}`)
func main() {
n := int(gjson.GetBytes(json, "friends.#").Int())
for i := 0; i < n; i++ {
path := fmt.Sprintf("friends.%d.last", i)
var err error
json, err = sjson.DeleteBytes(json, path)
if err != nil {
log.Fatal(err)
}
}
println(string(json))
}
@tidwall
Copy link
Author

tidwall commented Feb 9, 2017

Should output

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "age": 44},
    {"first": "Roger", "age": 68},
    {"first": "Jane", "age": 47}
  ]
}

@nilslice
Copy link

nilslice commented Feb 9, 2017

Came to pretty much the same conclusion -- thank you for looking into this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment