This Go library is for retrieving a part of JSON according to the JSONPath query syntax.
The core JSONPath syntax on which this library based:
- Stefan Gössner's JSONPath - XPath for JSON
- Christoph Burgmer's json-path-comparison
- JSONPath Internet Draft Development
For syntax compatibility among other libraries, please check 📝 my comparison results.
go get github.com/AsaiYusuke/jsonpath
package main
import (
"encoding/json"
"fmt"
"github.com/AsaiYusuke/jsonpath"
)
func main() {
jsonPath, srcJSON := `$.key`, `{"key":"value"}`
var src interface{}
json.Unmarshal([]byte(srcJSON), &src)
output, _ := jsonpath.Retrieve(jsonPath, src)
outputJSON, _ := json.Marshal(output)
fmt.Println(string(outputJSON))
// Output:
// ["value"]
}
- The JSONPath syntax analysis functionality has been separated using PEG, resulting in a more simplified source code.
- Robust unit testing has been implemented to prevent bugs and ensure consistent outcomes.
- The library is equipped with a comprehensive error specification, allowing users to effectively handle any errors that may arise.
- The library has integrated a greater level of consensus behavior from Christoph Burgmer's json-path-comparison, ensuring seamless compatibility.
The Retrieve
function returns retrieved result using JSONPath and JSON object:
output, err := jsonpath.Retrieve(jsonPath, src)
The Parse
function returns a parser-function that completed to check JSONPath syntax.
By using parser-function, it can repeat to retrieve with the same JSONPath :
jsonPath, err := jsonpath.Parse(jsonPath)
output1, err1 := jsonPath(src1)
output2, err2 := jsonPath(src2)
:
If there is a problem with the execution of APIs, an error type returned. These error types define the corresponding symptom, as listed below:
Error type | Message format | Symptom | Ex |
---|---|---|---|
ErrorInvalidSyntax |
invalid syntax (position=%d, reason=%s, near=%s) |
The invalid syntax found in the JSONPath. The reason including in this message will tell you more about it. |
📝 |
ErrorInvalidArgument |
invalid argument (argument=%s, error=%s) |
The argument specified in the JSONPath treated as the invalid error in Go syntax. | 📝 |
ErrorFunctionNotFound |
function not found (function=%s) |
The function specified in the JSONPath is not found. | 📝 |
ErrorNotSupported |
not supported (feature=%s, path=%s) |
The unsupported syntaxes specified in the JSONPath. | 📝 |
Error type | Message format | Symptom | Ex |
---|---|---|---|
ErrorMemberNotExist |
member did not exist (path=%s) |
The object/array member specified in the JSONPath did not exist in the JSON object. | 📝 |
ErrorTypeUnmatched |
type unmatched (expected=%s, found=%s, path=%s) |
The node type specified in the JSONPath did not exist in the JSON object. | 📝 |
ErrorFunctionFailed |
function failed (function=%s, error=%s) |
The function specified in the JSONPath failed. | 📝 |
The type checking is convenient to recognize which error happened.
:
_,err := jsonpath.Retrieve(jsonPath, srcJSON)
if err != nil {
switch err.(type) {
case jsonpath.ErrorMemberNotExist:
fmt.printf(`retry with other srcJSON: %v`, err)
continue
case jsonpath.ErrorInvalidArgumentFormat:
return nil, fmt.errorf(`specified invalid argument: %v`, err)
}
:
}
Function enables to format results by using user defined functions. The function syntax comes after the JSONPath.
There are two ways to use function:
The filter function applies a user function to each values in the result to get converted.
The aggregate function converts all values in the result into a single value.
You can get the accessors ( Getters / Setters ) of the input JSON instead of the retrieved values. These accessors can use to update for the input JSON.
This feature can get enabled by giving Config.SetAccessorMode()
.
It is not possible to use Setter for some results, such as for JSONPath including function syntax.
Also, operations using accessors follow the map/slice manner of Go language. If you use accessors after changing the structure of JSON, you need to pay attention to the behavior. If you don't want to worry about it, get the accessor again every time you change the structure.
Some behaviors that differ from the consensus exists in this library. For the entire comparisons, please check 📝 this result.
These behaviors will change in the future if appropriate ones found.
The following character types can be available for identifiers in dot-child notation.
Character type | Available | Escape required |
---|---|---|
* Numbers and alphabets (0-9 A-Z a-z )* Hyphen and underscore ( - _ )* Non-ASCII Unicode characters ( 0x80 - 0x10FFFF ) |
Yes | No |
* Other printable symbols (Space ! " # $ % & ' ( ) * + , . / : ; < = > ? @ [ \ ] ^ ` { | } ~ ) |
Yes | Yes |
* 0x00 - 0x1F , 0x7F ) |
No | - |
The printable symbols except hyphen and underscore can use by escaping them.
JSONPath : $.abc\.def
srcJSON : {"abc.def":1}
Output : [1]
The wildcards in qualifier can specify as a union of subscripts.
JSONPath : $[0,1:3,*]
srcJSON : [0,1,2,3,4,5]
Output : [0,1,2,0,1,2,3,4,5]
The regular expression syntax works as a regular expression in Go lang. In particular, you can use "(?i)" to specify the regular expression as the ignore case option.
JSONPath : $[?(@=~/(?i)CASE/)]
srcJSON : ["Case","Hello"]
Output : ["Case"]
JSONPaths that return a value group cannot use with comparator
or regular expression
. However, existence check
can use these syntaxes.
JSONPaths that return a value group | example |
---|---|
Recursive descent | @..a |
Multiple identifier | @['a','b'] |
Wildcard identifier | @.* |
Slice qualifier | @[0:1] |
Wildcard qualifier | @[*] |
Union in the qualifier | @[0,1] |
Filter qualifier | @.a[?(@.b)] |
- comparator example (error)
JSONPath : $[?(@..x == "hello world")]
srcJSON : [{"a":1},{"b":{"x":"hello world"}}]
Error : ErrorInvalidSyntax
- regular expression example (error)
JSONPath : $[?(@..x=~/hello/)]
srcJSON : [{"a":1},{"b":{"x":"hello world"}}]
Error : ErrorInvalidSyntax
- existence check example
JSONPath : $[?(@..x)]
srcJSON : [{"a":1},{"b":{"x":"hello world"}}]
Output : [{"b":{"x":"hello world"}}]
JSONPath filter that begins with Root is a whole-match operation when any one is detected.
JSONPath : $[?($..x)]
srcJSON : [{"a":1},{"b":{"x":"hello world"}}]
Output : [{"a":1},{"b":{"x":"hello world"}}]
The benchmarks for various JSONPath libraries in Go language can be compared in the following repository.
- Syntax
- Identifier
- identifier in dot notations
- identifier in bracket notations
- wildcard
- multiple-identifier in bracket
- recursive retrieve
- Qualifier
- index
- slice
- wildcard
- Filter
- logical operation
- comparator
- JSONPath retrieve in filter
- script
- Function
- filter
- aggregate
- Refer to the consensus behaviors
- Identifier
- Architecture
- PEG syntax analyzing
- Error handling
- Function
- Accessing JSON
- Go language manner
- retrieve with the object in interface unmarshal
- retrieve with the json.Number type
- Source code
- Release version
- Unit tests
- syntax tests
- benchmark
- coverage >80%
- Examples
- CI automation
- Documentation
- README
- API doc
- comparison result (local)
- Development status
- determine requirements / functional design
- design-based coding
- testing
- documentation
- Future ToDo
- Refer to the something standard
- Go language affinity
- retrieve with the object in struct unmarshal
- retrieve with the struct tags
- retrieve with the user defined objects