-
Notifications
You must be signed in to change notification settings - Fork 139
Configurations
Saddam H edited this page Mar 11, 2020
·
6 revisions
Sometime you may prefer to use the third party JSON decoder over GO's default JSON decoder.
From gojsonq
version v1.6 custom JSON decoder can be used, in order to use custom decoder you have to pass the decoder as option
.
See example below:
package main
import (
"github.com/davecgh/go-spew/spew"
jsoniter "github.com/json-iterator/go"
"github.com/pquerna/ffjson/ffjson"
gojsonq "github.com/thedevsaddam/gojsonq/v2"
)
func main() {
jq := gojsonq.New(gojsonq.SetDecoder(&iteratorDecoder{})).
File("./data.json").
From("vendor.items").
Where("id", "=", 1).OrWhere("id", "=", 3)
spew.Dump("Result: ", jq.Only("name", "id"), jq.Error())
}
type iteratorDecoder struct {
}
func (i *iteratorDecoder) Decode(data []byte, v interface{}) error {
var json = jsoniter.ConfigCompatibleWithStandardLibrary
return json.Unmarshal(data, &v)
}
type ffDecoder struct {
}
func (f *ffDecoder) Decode(data []byte, v interface{}) error {
return ffjson.Unmarshal(data, &v)
}
You may need to use a custom separator instead of default DOT (.)
separator. You can set a custom separator/traverser notation from gojsonq
version v2.0. See the example below:
package main
import (
"fmt"
gojsonq "github.com/thedevsaddam/gojsonq/v2"
)
func main() {
jq := gojsonq.New(gojsonq.SetSeparator("->")).File("./data.json")
res := jq.Find("items->[0]->name")
fmt.Printf("%#v\n", res) //Output: "MacBook Pro 13 inch retina"
}
If you find the package useful please don't forget to star the repository