jsonpath icon indicating copy to clipboard operation
jsonpath copied to clipboard

jsonpath golang library to help with getting and setting values on paths (even nonexistent paths)

jsonpath build Go Report Card GoDoc

Originally intended to be used with json.Unmarshal, this is a golang library used to able get and set jsonpaths (even nonexistent paths).

Install

$ go get github.com/mdaverde/jsonpath

Usage

sample := `{ "owner": { "name": "john doe", "contact": { "phone": "555-555-5555" } } }`

var payload interface{}

err := json.Unmarshal([]byte(sample), &payload)
must(err)

err = jsonpath.Set(&payload, "owner.contact.phone", "333-333-3333")
must(err)

value, err := jsonpath.Get(payload, "owner.contact.phone")
must(err)

// value == "333-333-3333"

API

jsonpath.Get(data interface{}, path string) (interface{}, error)

Returns the value at that json path as interface{} and if an error occurred

jsonpath.Set(data interface{}, path string, value interface{}) (error)

Sets value on data at that json path

Note: you'll want to pass in a pointer to data so that the side effect actually is usable

jsonpath.DoesNotExist error

Returned by jsonpath.Get on a nonexistent path:

value, err := Get(data, "where.is.this")
if _, ok := err.(DoesNotExist); !ok && err != nil {
    // other error
}

Testing

$ go test .

License

MIT © mdaverde