jp

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2023 License: MIT Imports: 6 Imported by: 0

README

jp: JSON Pointers for Raw JSON Content

GoDoc

jp is a Go package that provides access to raw JSON content using RFC 6901 JSON pointers.

jp is derived from GJSON.

Installing

To start using jp, install Go and run go get:

$ go get -u github.com/pgavlin/jp

This will retrieve the library.

Get a value

Get searches JSON content for the specified pointer. A pointer is in JSON pointer syntax, such as "/name/last" or "/age". When the value is found it's returned immediately.

package main

import "github.com/pgavlin/jp"

const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
	value := jp.Get(json, "/name/last")
	println(value.String())
}

This will print:

Prichard

There's also the GetMany function to get multiple values at once, and GetBytes for working with JSON byte slices.

Pointer Syntax

Below is a quick overview of the pointer syntax, for more complete information please see RFC 6901.

  • A pointer is a series of keys separated by /
  • An array elements is accessed using its base-10 index as its key
  • If they appear in aa key, the ~ and / characters must be escaped as ~0 and ~1, respectively
{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]
}
"/name/last"          >> "Anderson"
"/age"                >> 37
"/children"           >> ["Sara","Alex","Jack"]
"/children/1"         >> "Alex"
"/fav.movie"          >> "Deer Hunter"
"/friends/1/last"     >> "Craig"

Result Type

jp supports the json types string, number, bool, and null. Arrays and Objects are returned as their raw json types.

The Result type holds one of these:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON string literals
nil, for JSON null

To directly access the value:

result.Type           // can be String, Number, True, False, Null, or JSON
result.Str            // holds the string
result.Num            // holds the float64 number
result.Raw            // holds the raw json
result.Index          // index of raw value in original json, zero means index unknown

There are a variety of handy functions that work on a result:

result.Exists() bool
result.Value() interface{}
result.Int() int64
result.Uint() uint64
result.Float() float64
result.String() string
result.Bool() bool
result.Time() time.Time
result.Array() []jp.Result
result.Map() map[string]jp.Result
result.Get(pointer string) jp.Result
result.Range() *jp.Iterator
result.ForEach(iterator func(key, value jp.Result) bool)
result.Less(token jp.Result, caseSensitive bool) bool

The result.Value() function returns an interface{} which requires type assertion and is one of the following Go types:

boolean >> bool
number  >> float64
string  >> string
null    >> nil
array   >> []interface{}
object  >> map[string]interface{}

The result.Array() function returns back an array of values. If the result represents a non-existent value, then an empty array will be returned. If the result is not a JSON array, the return value will be an array containing one result.

64-bit integers

The result.Int() and result.Uint() calls are capable of reading all 64 bits, allowing for large JSON integers.

result.Int() int64    // -9223372036854775808 to 9223372036854775807
result.Uint() int64   // 0 to 18446744073709551615

Iterate through an object or array

The ForEach function allows for quickly iterating through an object or array. The key and value are passed to the iterator function for objects. The element index and value aare passed for arrays. Returning false from an iterator will stop iteration.

result := jp.Get(json, "/programmers")
result.ForEach(func(key, value jp.Result) bool {
	println(value.String()) 
	return true // keep iterating
})

Alternatively, the Range function allows the caller to drive iteration:

result := jp.Get(json, "/programmers")
for it := result.Range(); it.Next(); {
	println(value.String())
}

Simple Parse and Get

There's a Parse(json) function that will do a simple parse, and result.Get(pointer) that will search a result.

For example, all of these will return the same result:

jp.Parse(json).Get("/name").Get("/last")
jp.Get(json, "/name").Get("/last")
jp.Get(json, "/name/last")

Check for the existence of a value

Sometimes you just want to know if a value exists.

value := jp.Get(json, "/name/last")
if !value.Exists() {
	println("no last name")
} else {
	println(value.String())
}

// Or as one step
if jp.Get(json, "/name/last").Exists() {
	println("has a last name")
}

Validate JSON

The Get* and Parse* functions expects that the json is well-formed. Bad json will not panic, but it may return back unexpected results.

If you are consuming JSON from an unpredictable source then you may want to validate prior to using GJSON.

if !jp.Valid(json) {
	return errors.New("invalid json")
}
value := jp.Get(json, "/name/last")

Unmarshal to a map

To unmarshal to a map[string]interface{}:

m, ok := jp.Parse(json).Value().(map[string]interface{})
if !ok {
	// not a map
}

Working with Bytes

If your JSON is contained in a []byte slice, there's the GetBytes function. This is preferred over Get(string(data), pointer).

var json []byte = ...
result := jp.GetBytes(json, pointer)

If you are using the jp.GetBytes(json, pointer) function and you want to avoid converting result.Raw to a []byte, then you can use this pattern:

var json []byte = ...
result := jp.GetBytes(json, pointer)
var raw []byte
if result.Index > 0 {
    raw = json[result.Index:result.Index+len(result.Raw)]
} else {
    raw = []byte(result.Raw)
}

This is a best-effort no allocation sub slice of the original json. This method utilizes the result.Index field, which is the position of the raw data in the original json. It's possible that the value of result.Index equals zero, in which case the result.Raw is converted to a []byte.

Get multiple values at once

The GetMany function can be used to get multiple values at the same time.

results := jp.GetMany(json, "/name/first", "/name/last", "/age")

The return value is a []Result, which will always contain exactly the same number of items as the input pointers.

Documentation

Overview

Package jp provides pointers for json strings.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Valid

func Valid(json string) bool

Valid returns true if the input is valid json.

if !jp.Valid(json) {
	return errors.New("invalid json")
}
value := jp.Get(json, "name.last")

func ValidBytes

func ValidBytes(json []byte) bool

ValidBytes returns true if the input is valid json.

if !jp.Valid(json) {
	return errors.New("invalid json")
}
value := jp.Get(json, "name.last")

If working with bytes, this method preferred over ValidBytes(string(data))

Types

type Iterator

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

func (*Iterator) Key

func (it *Iterator) Key() Result

func (*Iterator) Next

func (it *Iterator) Next() bool

func (*Iterator) Value

func (it *Iterator) Value() Result

type Result

type Result struct {
	// Type is the json type
	Type Type
	// Raw is the raw json
	Raw string
	// Str is the json string
	Str string
	// Num is the json number
	Num float64
	// Index of raw value in original json, zero means index unknown
	Index int
}

Result represents a json value that is returned from Get().

func Get

func Get(json, pointer string) Result

Get searches json for the specified RFC 6901 JSON pointer.

This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.

func GetBytes

func GetBytes(json []byte, path string) Result

GetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)

func GetMany

func GetMany(json string, path ...string) []Result

GetMany searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.

func GetManyBytes

func GetManyBytes(json []byte, path ...string) []Result

GetManyBytes searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.

func Parse

func Parse(json string) Result

Parse parses the json and returns a result.

This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.

func ParseBytes

func ParseBytes(json []byte) Result

ParseBytes parses the json and returns a result. If working with bytes, this method preferred over Parse(string(data))

func (Result) Array

func (t Result) Array() []Result

Array returns back an array of values. If the result represents a null value or is non-existent, then an empty array will be returned. If the result is not a JSON array, the return value will be an array containing one result.

func (Result) Bool

func (t Result) Bool() bool

Bool returns an boolean representation.

func (Result) Exists

func (t Result) Exists() bool

Exists returns true if value exists.

 if jp.Get(json, "name.last").Exists(){
		println("value exists")
 }

func (Result) Float

func (t Result) Float() float64

Float returns an float64 representation.

func (Result) ForEach

func (t Result) ForEach(iterator func(key, value Result) bool)

ForEach iterates through values. If the result represents a non-existent value, then no values will be iterated. If the result is an Object, the iterator will pass the key and value of each item. If the result is an Array, the iterator will pass the index and value of each item.

func (Result) Get

func (t Result) Get(path string) Result

Get searches result for the specified path. The result should be a JSON array or object.

func (Result) Int

func (t Result) Int() int64

Int returns an integer representation.

func (Result) IsArray

func (t Result) IsArray() bool

IsArray returns true if the result value is a JSON array.

func (Result) IsBool

func (t Result) IsBool() bool

IsBool returns true if the result value is a JSON boolean.

func (Result) IsObject

func (t Result) IsObject() bool

IsObject returns true if the result value is a JSON object.

func (Result) Len

func (t Result) Len() int

Len returns the length of the result if the result is an object or array.

func (Result) Less

func (t Result) Less(token Result, caseSensitive bool) bool

Less return true if a token is less than another token. The caseSensitive paramater is used when the tokens are Strings. The order when comparing two different type is:

Null < False < Number < String < True < JSON

func (Result) Map

func (t Result) Map() map[string]Result

Map returns back a map of values. The result should be a JSON object. If the result is not a JSON object, the return value will be an empty map.

func (Result) Range

func (t Result) Range() *Iterator

func (Result) String

func (t Result) String() string

String returns a string representation of the value.

func (Result) Time

func (t Result) Time() time.Time

Time returns a time.Time representation.

func (Result) Uint

func (t Result) Uint() uint64

Uint returns an unsigned integer representation.

func (Result) Value

func (t Result) Value() interface{}

Value returns one of these types:

bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null
map[string]interface{}, for JSON objects
[]interface{}, for JSON arrays

type Type

type Type int

Type is Result type

const (
	// Null is a null json value
	Null Type = iota
	// False is a json false boolean
	False
	// Number is json number
	Number
	// String is a json string
	String
	// True is a json true boolean
	True
	// JSON is a raw block of JSON
	JSON
)

func (Type) String

func (t Type) String() string

String returns a string representation of the type.

Jump to

Keyboard shortcuts

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