jpath

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2022 License: BSD-3-Clause Imports: 11 Imported by: 5

README

JSON Path GoDoc

A go package and a set of utilities for interacting with arbitrary JSON data.

Example usage
package main

import (
    "fmt"
    "github.com/xyproto/jpath"
    "log"
)

func main() {
    // Some JSON
    data := []byte(`{"a":2, "b":3, "people":{"names": ["Bob", "Alice"]}}`)

    // Create a new *jpath.Node
    document, err := jpath.New(data)
    if err != nil {
        log.Fatal(err)
    }

    // Retrieve the value of "a", as an int
    val := document.Get("a").Int()
    fmt.Println("a is", val)

    // Retrieve the first name, using a path expression
    name := document.GetNode(".people.names[0]").String()
    fmt.Println("The name is", name)
}
Installation
go get github.com/xyproto/jpath/cmd/...
Path expressions

Several of the available functions takes a simple JSON path expression, like x.books[1].author. Only simple expressions using x for the root node, names and integer indexes are supported as part of the path. For more advanced JSON path expressions, see this blog post.

The SetBranch method for the Node struct also provides a way of accessing JSON nodes, where the JSON names are supplied as a slice of strings.

Utilities

Four small utilities for interacting with JSON files are included. Note that these deals with strings only, not numbers or anything else!

  • jget - for retrieving a string value from a JSON file. Takes a filename and a simple JSON path expression.
    • Example: jget books.json x[1].author
  • jset - for setting JSON string values in a JSON file. Takes a filename, simple JSON path expression and a string.
    • Example: jset books.json x[1].author Suzanne
  • jdel - for removing a key from a map in a JSON file. Takes a filename and a simple JSON path expression.
    • Example: jdel abc.json b
  • jadd - for adding JSON data to a JSON file. Takes a filename, simple JSON path expression and JSON data.
    • Example: jadd books.json x '{"author": "Joan Grass", "book": "The joys of gardening"}'
General information

Documentation

Overview

Package jpath provides a way to search and manipulate JSON documents

Index

Constants

View Source
const Version = 1.0

Version contains the version number. The API is stable within the same major version.

Variables

View Source
var (
	NilNode        = &Node{nil}
	ErrKeyNotFound = errors.New("key not found")
)

NilNode is an empty node. Used when not finding nodes with Get.

View Source
var (
	// ErrSpecificNode is for when retrieving a node does not return a specific key/value, but perhaps a map
	ErrSpecificNode = errors.New("could not find a specific node that matched the given path")
)

Functions

func AddJSON

func AddJSON(filename, JSONpath string, JSONdata []byte, pretty bool) error

AddJSON adds JSON data to the given JSON file at the given JSON path

func DelKey

func DelKey(filename, JSONpath string) error

DelKey removes a key from a map in a JSON file, given a JSON path, where the last element of the path is the key to be removed.

func GetString

func GetString(filename, JSONpath string) (string, error)

GetString will find the string that corresponds to the given JSON path, given a filename and a simple JSON path expression.

func SetString

func SetString(filename, JSONpath, value string) error

SetString sets a value to the given JSON file at the given JSON path

Types

type JFile

type JFile struct {
	// contains filtered or unexported fields
}

JFile represents a JSON file and contains the filename and root node

func NewFile

func NewFile(filename string) (*JFile, error)

NewFile will read the given filename and return a JFile struct

func (*JFile) AddJSON

func (jf *JFile) AddJSON(JSONpath string, JSONdata []byte) error

AddJSON adds JSON data at the given JSON path. If pretty is true, the JSON is indented.

func (*JFile) DelKey

func (jf *JFile) DelKey(JSONpath string) error

DelKey removes a key from the map that the JSON path leads to. Returns ErrKeyNotFound if the key is not found.

func (*JFile) GetFilename

func (jf *JFile) GetFilename() string

GetFilename returns the current filename

func (*JFile) GetNode

func (jf *JFile) GetNode(JSONpath string) (*Node, error)

GetNode tries to find the JSON node that corresponds to the given JSON path

func (*JFile) GetString

func (jf *JFile) GetString(JSONpath string) (string, error)

GetString tries to find the string that corresponds to the given JSON path

func (*JFile) JSON

func (jf *JFile) JSON() ([]byte, error)

JSON returns the current JSON data, as prettily formatted JSON

func (*JFile) SetPretty

func (jf *JFile) SetPretty(pretty bool)

SetPretty can be used for setting the "pretty" flag to true, for indenting all JSON output. Set to true by default.

func (*JFile) SetRW

func (jf *JFile) SetRW(rw *sync.RWMutex)

SetRW allows a different mutex to be used when writing the JSON documents to file

func (*JFile) SetString

func (jf *JFile) SetString(JSONpath, value string) error

SetString will change the value of the key that the given JSON path points to

func (*JFile) Write

func (jf *JFile) Write(data []byte) error

Write writes the current JSON data to the file

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is a JSON document, or a part of a JSON document

func New

func New(body []byte) (*Node, error)

New returns a pointer to a new `Node` object after unmarshaling `body` bytes

func NewFromReader

func NewFromReader(r io.Reader) (*Node, error)

NewFromReader returns a *Node by decoding from an io.Reader

func NewNode

func NewNode() *Node

NewNode returns a pointer to a new, empty `Node` object

func (*Node) AddJSON

func (j *Node) AddJSON(JSONpath string, JSONdata []byte) error

AddJSON adds JSON data to a list. The JSON path must refer to a list.

func (*Node) Bool

func (j *Node) Bool(args ...bool) bool

Bool guarantees the return of a `bool` (with optional default)

useful when you explicitly want a `bool` in a single value return context:

myFunc(js.Get("param1").Bool(), js.Get("optional_param").Bool(true))

func (*Node) CheckBool

func (j *Node) CheckBool() (bool, bool)

CheckBool type asserts to `bool`

func (*Node) CheckFloat64

func (j *Node) CheckFloat64() (float64, bool)

CheckFloat64 coerces into a float64

func (*Node) CheckGet

func (j *Node) CheckGet(branch ...interface{}) (*Node, bool)

CheckGet is like Get, except it also returns a bool indicating whenever the branch was found or not the Node pointer may be nil

newJs, ok := js.Get("top_level", "entries", 3, "dict")

func (*Node) CheckInt

func (j *Node) CheckInt() (int, bool)

CheckInt coerces into an int

func (*Node) CheckInt64

func (j *Node) CheckInt64() (int64, bool)

CheckInt64 coerces into an int64

func (*Node) CheckList

func (j *Node) CheckList() ([]interface{}, bool)

CheckList type asserts to a slice

func (*Node) CheckMap

func (j *Node) CheckMap() (map[string]interface{}, bool)

CheckMap type asserts to `map`

func (*Node) CheckNodeList

func (j *Node) CheckNodeList() ([]*Node, bool)

CheckNodeList returns a copy of a slice, but with each value as a Node

func (*Node) CheckNodeMap

func (j *Node) CheckNodeMap() (NodeMap, bool)

CheckNodeMap returns a copy of a Node map, but with values as Nodes

func (*Node) CheckString

func (j *Node) CheckString() (string, bool)

CheckString type asserts to `string`

func (*Node) CheckUint64

func (j *Node) CheckUint64() (uint64, bool)

CheckUint64 coerces into an uint64

func (*Node) DelKey

func (j *Node) DelKey(JSONpath string) error

DelKey removes a key in a map, given a JSON path to a map. Returns ErrKeyNotFound if the key is not found.

func (*Node) Float64

func (j *Node) Float64(args ...float64) float64

Float64 guarantees the return of a `float64` (with optional default)

useful when you explicitly want a `float64` in a single value return context:

myFunc(js.Get("param1").Float64(), js.Get("optional_param").Float64(5.150))

func (*Node) Get

func (j *Node) Get(branch ...interface{}) *Node

Get searches for the item as specified by the branch within a nested Node and returns a new Node pointer the pointer is always a valid Node, allowing for chained operations

newJs := js.Get("top_level", "entries", 3, "dict")

func (*Node) GetIndex

func (j *Node) GetIndex(index int) (*Node, bool)

GetIndex returns a pointer to a new `Node` object for `index` in its slice representation and a bool identifying success or failure

func (*Node) GetKey

func (j *Node) GetKey(key string) (*Node, bool)

GetKey returns a pointer to a new `Node` object for `key` in its `map` representation and a bool identifying success or failure

func (*Node) GetNode

func (j *Node) GetNode(JSONpath string) *Node

GetNode will find the JSON node that corresponds to the given JSON path, or nil.

func (*Node) GetNodes

func (j *Node) GetNodes(JSONpath string) (*Node, *Node, error)

GetNodes will find the JSON node (and parent node) that corresponds to the given JSON path

func (*Node) Info

func (j *Node) Info() string

Info returns a description of the node

func (*Node) Int

func (j *Node) Int(args ...int) int

Int guarantees the return of an `int` (with optional default)

useful when you explicitly want an `int` in a single value return context:

myFunc(js.Get("param1").Int(), js.Get("optional_param").Int(5150))

func (*Node) Int64

func (j *Node) Int64(args ...int64) int64

Int64 guarantees the return of an `int64` (with optional default)

useful when you explicitly want an `int64` in a single value return context:

myFunc(js.Get("param1").Int64(), js.Get("optional_param").Int64(5150))

func (*Node) Interface

func (j *Node) Interface() interface{}

Interface returns the underlying data

func (*Node) JSON

func (j *Node) JSON() ([]byte, error)

JSON returns its marshaled data as `[]byte`

func (*Node) List

func (j *Node) List(args ...[]interface{}) []interface{}

List guarantees the return of a `[]interface{}` (with optional default)

useful when you want to interate over array values in a succinct manner:

for i, v := range js.Get("results").List() {
	fmt.Println(i, v)
}

func (*Node) Map

func (j *Node) Map(args ...map[string]interface{}) map[string]interface{}

Map guarantees the return of a `map[string]interface{}` (with optional default)

useful when you want to interate over map values in a succinct manner:

for k, v := range js.Get("dictionary").Map() {
	fmt.Println(k, v)
}

func (*Node) MarshalJSON

func (j *Node) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*Node) MustJSON

func (j *Node) MustJSON() []byte

MustJSON returns its marshaled data as `[]byte`

func (*Node) NodeList

func (j *Node) NodeList(args ...NodeList) NodeList

NodeList guarantees the return of a `[]*Node` (with optional default)

func (*Node) NodeMap

func (j *Node) NodeMap(args ...NodeMap) NodeMap

NodeMap guarantees the return of a `map[string]*Node` (with optional default)

func (*Node) PrettyJSON

func (j *Node) PrettyJSON() ([]byte, error)

PrettyJSON returns its marshaled data as `[]byte` with indentation

func (*Node) Set

func (j *Node) Set(key string, val interface{})

Set modifies `Node` map by `key` and `value` Useful for changing single key/value in a `Node` object easily.

func (*Node) SetBranch

func (j *Node) SetBranch(branch []string, val interface{})

SetBranch modifies `Node`, recursively checking/creating map keys for the supplied path, and then finally writing in the value.

func (*Node) String

func (j *Node) String(args ...string) string

String guarantees the return of a `string` (with optional default)

useful when you explicitly want a `string` in a single value return context:

myFunc(js.Get("param1").String(), js.Get("optional_param").String("my_default"))

func (*Node) Uint64

func (j *Node) Uint64(args ...uint64) uint64

Uint64 guarantees the return of an `uint64` (with optional default)

useful when you explicitly want an `uint64` in a single value return context:

myFunc(js.Get("param1").Uint64(), js.Get("optional_param").Uint64(5150))

func (*Node) UnmarshalJSON

func (j *Node) UnmarshalJSON(p []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type NodeList

type NodeList []*Node

NodeList is a list of nodes

type NodeMap

type NodeMap map[string]*Node

NodeMap is a map of nodes

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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