jsonpath

package module
Version: v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2021 License: MIT Imports: 5 Imported by: 3

README

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

Documentation

Overview

Package jsonpath implements getter and setter for generic JSON unmarshaled data structures (i.e. map[string]interface{})

Values can be set on nonexistent paths.

Path strings are not 100% JSONPath compliant (yet) but will handle most of the common use cases.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(data interface{}, path string) (interface{}, error)

Get returns the value at the json path or if an error occurred

func Set

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

Set value on data at that json path

Types

type DoesNotExist

type DoesNotExist struct{}

DoesNotExist is returned by jsonpath.Get on nonexistent paths

func (DoesNotExist) Error

func (d DoesNotExist) Error() string

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL