Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

json source pure

Readme View source

JSON Parser

The JSON parser is a package that provides functionality for parsing and processing JSON strings. This package accepts JSON strings as byte slices.

Currently, gno does not support the reflect package, so it cannot retrieve type information at runtime. Therefore, it is designed to infer and handle type information when parsing JSON strings using a state machine approach.

After passing through the state machine, JSON strings are represented as the Node type. The Node type represents nodes for JSON data, including various types such as ObjectNode, ArrayNode, StringNode, NumberNode, BoolNode, and NullNode.

This package provides methods for manipulating, searching, and extracting the Node type.

State Machine

To parse JSON strings, a finite state machine approach is used. The state machine transitions to the next state based on the current state and the input character while parsing the JSON string. Through this method, type information can be inferred and processed without reflect, and the amount of parser code can be significantly reduced.

The image below shows the state transitions of the state machine according to the states and input characters.

stateDiagram-v2
    [*] --> __: Start
    __ --> ST: String
    __ --> MI: Number
    __ --> ZE: Zero
    __ --> IN: Integer
    __ --> T1: Boolean (true)
    __ --> F1: Boolean (false)
    __ --> N1: Null
    __ --> ec: Empty Object End
    __ --> cc: Object End
    __ --> bc: Array End
    __ --> co: Object Begin
    __ --> bo: Array Begin
    __ --> cm: Comma
    __ --> cl: Colon
    __ --> OK: Success/End
    ST --> OK: String Complete
    MI --> OK: Number Complete
    ZE --> OK: Zero Complete
    IN --> OK: Integer Complete
    T1 --> OK: True Complete
    F1 --> OK: False Complete
    N1 --> OK: Null Complete
    ec --> OK: Empty Object Complete
    cc --> OK: Object Complete
    bc --> OK: Array Complete
    co --> OB: Inside Object
    bo --> AR: Inside Array
    cm --> KE: Expecting New Key
    cm --> VA: Expecting New Value
    cl --> VA: Expecting Value
    OB --> ST: String in Object (Key)
    OB --> ec: Empty Object
    OB --> cc: End Object
    AR --> ST: String in Array
    AR --> bc: End Array
    KE --> ST: String as Key
    VA --> ST: String as Value
    VA --> MI: Number as Value
    VA --> T1: True as Value
    VA --> F1: False as Value
    VA --> N1: Null as Value
    OK --> [*]: End

Examples

This package provides parsing functionality along with encoding and decoding functionality. The following examples demonstrate how to use this package.

Decoding

Decoding (or Unmarshaling) is the functionality that converts an input byte slice JSON string into a Node type.

The converted Node type allows you to modify the JSON data or search and extract data that meets specific conditions.

 1package main
 2
 3import (
 4    "gno.land/p/demo/json"
 5    "gno.land/p/nt/ufmt/v0"
 6)
 7
 8func main() {
 9    node, err := json.Unmarshal([]byte(`{"foo": "var"}`))
10    if err != nil {
11        ufmt.Errorf("error: %v", err)
12    }
13
14    ufmt.Sprintf("node: %v", node)
15}

Encoding

Encoding (or Marshaling) is the functionality that converts JSON data represented as a Node type into a byte slice JSON string.

⚠️ Caution: Converting a large Node type into a JSON string may impact performance. or might be cause unexpected behavior.

 1package main
 2
 3import (
 4    "gno.land/p/demo/json"
 5    "gno.land/p/nt/ufmt/v0"
 6)
 7
 8func main() {
 9    node := ObjectNode("", map[string]*Node{
10        "foo": StringNode("foo", "bar"),
11        "baz": NumberNode("baz", 100500),
12        "qux": NullNode("qux"),
13    })
14
15    b, err := json.Marshal(node)
16    if err != nil {
17        ufmt.Errorf("error: %v", err)
18    }
19
20    ufmt.Sprintf("json: %s", string(b))
21}

Searching

Once the JSON data converted into a Node type, you can search and extract data that satisfy specific conditions. For example, you can find data with a specific type or data with a specific key.

To use this functionality, you can use methods in the GetXXX prefixed methods. The MustXXX methods also provide the same functionality as the former methods, but they will panic if data doesn't satisfies the condition.

Here is an example of finding data with a specific key. For more examples, please refer to the node.gno file.

 1package main
 2
 3import (
 4    "gno.land/p/demo/json"
 5    "gno.land/p/nt/ufmt/v0"
 6)
 7
 8func main() {
 9    root, err := Unmarshal([]byte(`{"foo": true, "bar": null}`))
10    if err != nil {
11        ufmt.Errorf("error: %v", err)
12    }
13
14    value, err := root.GetKey("foo")
15    if err != nil {
16        ufmt.Errorf("error occurred while getting key, %s", err)
17    }
18
19    if value.MustBool() != true {
20        ufmt.Errorf("value is not true")
21    }
22
23    value, err = root.GetKey("bar")
24    if err != nil {
25        t.Errorf("error occurred while getting key, %s", err)
26    }
27
28    _, err = root.GetKey("baz")
29    if err == nil {
30        t.Errorf("key baz is not exist. must be failed")
31    }
32}

Contributing

Please submit any issues or pull requests for this package through the GitHub repository at gnolang/gno.

Constants 3

const C_SPACE, C_WHITE, C_LCURB, C_RCURB, C_LSQRB, C_RSQRB, C_COLON, C_COMMA, C_QUOTE, C_BACKS, C_SLASH, C_PLUS, C_MINUS, C_POINT, C_ZERO, C_DIGIT, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_LOW_L, C_LOW_N, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ABCDF, C_E, C_ETC

 1const (
 2	C_SPACE Classes = iota /* space */
 3	C_WHITE                /* other whitespace */
 4	C_LCURB                /* {  */
 5	C_RCURB                /* } */
 6	C_LSQRB                /* [ */
 7	C_RSQRB                /* ] */
 8	C_COLON                /* : */
 9	C_COMMA                /* , */
10	C_QUOTE                /* " */
11	C_BACKS                /* \ */
12	C_SLASH                /* / */
13	C_PLUS                 /* + */
14	C_MINUS                /* - */
15	C_POINT                /* . */
16	C_ZERO                 /* 0 */
17	C_DIGIT                /* 123456789 */
18	C_LOW_A                /* a */
19	C_LOW_B                /* b */
20	C_LOW_C                /* c */
21	C_LOW_D                /* d */
22	C_LOW_E                /* e */
23	C_LOW_F                /* f */
24	C_LOW_L                /* l */
25	C_LOW_N                /* n */
26	C_LOW_R                /* r */
27	C_LOW_S                /* s */
28	C_LOW_T                /* t */
29	C_LOW_U                /* u */
30	C_ABCDF                /* ABCDF */
31	C_E                    /* E */
32	C_ETC                  /* everything else */
33)
source

enum classes

const GO, OK, OB, KE, CO, VA, AR, ST, ES, U1, U2, U3, U4, MI, ZE, IN, DT, FR, E1, E2, E3, T1, T2, T3, F1, F2, F3, F4, N1, N2, N3

 1const (
 2	GO States = iota /* start    */
 3	OK               /* ok       */
 4	OB               /* object   */
 5	KE               /* key      */
 6	CO               /* colon    */
 7	VA               /* value    */
 8	AR               /* array    */
 9	ST               /* string   */
10	ES               /* escape   */
11	U1               /* u1       */
12	U2               /* u2       */
13	U3               /* u3       */
14	U4               /* u4       */
15	MI               /* minus    */
16	ZE               /* zero     */
17	IN               /* integer  */
18	DT               /* dot      */
19	FR               /* fraction */
20	E1               /* e        */
21	E2               /* ex       */
22	E3               /* exp      */
23	T1               /* tr       */
24	T2               /* tru      */
25	T3               /* true     */
26	F1               /* fa       */
27	F2               /* fal      */
28	F3               /* fals     */
29	F4               /* false    */
30	N1               /* nu       */
31	N2               /* nul      */
32	N3               /* null     */
33)
source

The state codes.

Variables 3

var AsciiClasses

 1var AsciiClasses = [128]Classes{
 2
 3	__, __, __, __, __, __, __, __,
 4	__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
 5	__, __, __, __, __, __, __, __,
 6	__, __, __, __, __, __, __, __,
 7
 8	C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
 9	C_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
10	C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
11	C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
12
13	C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
14	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
15	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
16	C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,
17
18	C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
19	C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
20	C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
21	C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,
22}
source

AsciiClasses array maps the 128 ASCII characters into character classes.

var QuoteAsciiClasses

 1var QuoteAsciiClasses = [128]Classes{
 2
 3	__, __, __, __, __, __, __, __,
 4	__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
 5	__, __, __, __, __, __, __, __,
 6	__, __, __, __, __, __, __, __,
 7
 8	C_SPACE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,
 9	C_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
10	C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
11	C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
12
13	C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
14	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
15	C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
16	C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,
17
18	C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
19	C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
20	C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
21	C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,
22}
source

QuoteAsciiClasses is a HACK for single quote from AsciiClasses

var StateTransitionTable

 1var StateTransitionTable = [31][31]States{
 2
 3	{GO, GO, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
 4	{OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
 5	{OB, OB, __, ec, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
 6	{KE, KE, __, __, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
 7	{CO, CO, __, __, __, __, cl, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
 8	{VA, VA, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
 9	{AR, AR, co, __, bo, bc, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},
10	{ST, __, ST, ST, ST, ST, ST, ST, qt, ES, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST},
11	{__, __, __, __, __, __, __, __, ST, ST, ST, __, __, __, __, __, __, ST, __, __, __, ST, __, ST, ST, __, ST, U1, __, __, __},
12	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, U2, U2, U2, U2, U2, U2, U2, U2, __, __, __, __, __, __, U2, U2, __},
13	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, U3, U3, U3, U3, U3, U3, U3, U3, __, __, __, __, __, __, U3, U3, __},
14	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, U4, U4, U4, U4, U4, U4, U4, U4, __, __, __, __, __, __, U4, U4, __},
15	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, ST, ST, ST, ST, ST, ST, ST, ST, __, __, __, __, __, __, ST, ST, __},
16	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, ZE, IN, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
17	{OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, __, __, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
18	{OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, IN, IN, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
19	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, FR, FR, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
20	{OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, FR, FR, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},
21	{__, __, __, __, __, __, __, __, __, __, __, E2, E2, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
22	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
23	{OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
24	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T2, __, __, __, __, __, __},
25	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T3, __, __, __},
26	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},
27	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F2, __, __, __, __, __, __, __, __, __, __, __, __, __, __},
28	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F3, __, __, __, __, __, __, __, __},
29	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F4, __, __, __, __, __},
30	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},
31	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N2, __, __, __},
32	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N3, __, __, __, __, __, __, __, __},
33	{__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __},
34}
source

StateTransitionTable is the state transition table takes the current state and the current symbol, and returns either a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the text the state is OK and if the mode is DONE.

Functions 18

func Indent

1func Indent(data []byte, indent string) ([]byte, error)
source

IndentJSON formats the JSON data with the specified indentation.

func Marshal

1func Marshal(node *Node) ([]byte, error)
source

Marshal returns the JSON encoding of a Node.

func ParseBoolLiteral

1func ParseBoolLiteral(data []byte) (bool, error)
source

ParseBoolLiteral parses a boolean value from the given byte slice.

func ParsePath

1func ParsePath(path string) ([]string, error)
source

ParsePath takes a JSONPath string and returns a slice of strings representing the path segments.

func ParseStringLiteral

1func ParseStringLiteral(data []byte) (string, error)
source

PaseStringLiteral parses a string from the given byte slice.

func Unescape

1func Unescape(input, output []byte) ([]byte, error)
source

Unescape takes an input byte slice, processes it to Unescape certain characters, and writes the result into an output byte slice.

it returns the processed slice and any error encountered during the Unescape operation.

func Unquote

1func Unquote(s []byte, border byte) (string, bool)
source

Unquote takes a byte slice and unquotes it by removing the surrounding quotes and unescaping the contents.

func ArrayNode

1func ArrayNode(key string, value []*Node) *Node
source

ArrayNode creates a new array type node.

If the given value is nil, it creates an empty array node.

Usage:

Example
1root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
2if root == nil {
3	t.Errorf("ArrayNode returns nil")
4}

func BoolNode

1func BoolNode(key string, value bool) *Node
source

BoolNode creates a new given boolean value node.

Usage:

Example
1root := BoolNode("", true)
2if root == nil {
3	t.Errorf("BoolNode returns nil")
4}

func Must

1func Must(root *Node, expect error) *Node
source

Must panics if the given node is not fulfilled the expectation. Usage:

Example
1node := Must(Unmarshal([]byte(`{"key": "value"}`))

func NewNode

1func NewNode(prev *Node, b *buffer, typ ValueType, key **string) (*Node, error)
source

NewNode creates a new node instance with the given parent node, buffer, type, and key.

func NullNode

1func NullNode(key string) *Node
source

NullNode creates a new null type node.

Usage:

Example
1_ := NullNode("")

func NumberNode

1func NumberNode(key string, value float64) *Node
source

NumberNode creates a new number type node.

Usage:

Example
1root := NumberNode("", 1)
2if root == nil {
3	t.Errorf("NumberNode returns nil")
4}

func ObjectNode

1func ObjectNode(key string, value map[string]*Node) *Node
source

ObjectNode creates a new object type node.

If the given value is nil, it creates an empty object node.

next is a map of key and value pairs of the object.

func StringNode

1func StringNode(key string, value string) *Node
source

StringNode creates a new string type node.

Usage:

Example
1root := StringNode("", "foo")
2if root == nil {
3	t.Errorf("StringNode returns nil")
4}

func Unmarshal

1func Unmarshal(data []byte) (*Node, error)
source

Unmarshal parses the JSON-encoded data and returns a Node. The data must be a valid JSON-encoded value.

Usage:

Example
1node, err := json.Unmarshal([]byte(`{"key": "value"}`))
2if err != nil {
3	ufmt.Println(err)
4}
5println(node) // {"key": "value"}

func UnmarshalSafe

1func UnmarshalSafe(data []byte) (*Node, error)
source

UnmarshalSafe parses the JSON-encoded data and returns a Node.

Types 6

type ArrayBuilder

struct
1type ArrayBuilder struct {
2	nodes []*Node
3}
source

Methods on ArrayBuilder

func WriteArray

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteArray(fn func(*ArrayBuilder)) *ArrayBuilder
source

func WriteBool

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteBool(value bool) *ArrayBuilder
source

func WriteInt

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteInt(value int) *ArrayBuilder
source

func WriteNull

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteNull() *ArrayBuilder
source

func WriteNumber

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteNumber(value float64) *ArrayBuilder
source

func WriteObject

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteObject(fn func(*NodeBuilder)) *ArrayBuilder
source

func WriteString

method on ArrayBuilder
1func (ab *ArrayBuilder) WriteString(value string) *ArrayBuilder
source

type Node

struct
 1type Node struct {
 2	prev     *Node            // prev is the parent node of the current node.
 3	next     map[string]*Node // next is the child nodes of the current node.
 4	key      *string          // key holds the key of the current node in the parent node.
 5	data     []byte           // byte slice of JSON data
 6	value    any              // value holds the value of the current node.
 7	nodeType ValueType        // NodeType holds the type of the current node. (Object, Array, String, Number, Boolean, Null)
 8	index    *int             // index holds the index of the current node in the parent array node.
 9	borders  [2]int           // borders stores the start and end index of the current node in the data.
10	modified bool             // modified indicates the current node is changed or not.
11}
source

Node represents a JSON node.

Methods on Node

func AppendArray

method on Node
1func (n *Node) AppendArray(value ...*Node) error
source

AppendArray appends the given values to the current array node.

If the current node is not array type, it returns an error.

Example 1:

Example
1root := Must(Unmarshal([]byte(`[{"foo":"bar"}]`)))
2if err := root.AppendArray(NullNode("")); err != nil {
3	t.Errorf("should not return error: %s", err)
4}
5
6result: [{"foo":"bar"}, null]

Example 2:

Example
1root := Must(Unmarshal([]byte(`["bar", "baz"]`)))
2err := root.AppendArray(NumberNode("", 1), StringNode("", "foo"))
3if err != nil {
4	t.Errorf("AppendArray returns error: %v", err)
5 }
6
7result: ["bar", "baz", 1, "foo"]

func AppendObject

method on Node
1func (n *Node) AppendObject(key string, value *Node) error
source

AppendObject appends the given key and value to the current object node.

If the current node is not object type, it returns an error.

func ArrayEach

method on Node
1func (n *Node) ArrayEach(callback func(i int, target *Node))
source

ArrayEach executes the callback for each element in the JSON array.

Usage:

Example
1jsonArrayNode.ArrayEach(func(i int, valueNode *Node) {
2    ufmt.Println(i, valueNode)
3})

func Changed

method on Node
1func (n *Node) Changed() bool
source

Changed checks the current node is changed or not.

func Delete

method on Node
1func (n *Node) Delete() error
source

Delete removes the current node from the parent node.

Usage:

Example
1root := Unmarshal([]byte(`{"key": "value"}`))
2if err := root.MustKey("key").Delete(); err != nil {
3	t.Errorf("Delete returns error: %v", err)
4}
5
6result: {} (empty object)

func DeleteIndex

method on Node
1func (n *Node) DeleteIndex(idx int) error
source

DeleteIndex removes the array element at the given index.

func Empty

method on Node
1func (n *Node) Empty() bool
source

Empty returns true if the current node is empty.

func GetArray

method on Node
1func (n *Node) GetArray() ([]*Node, error)
source

GetArray returns the array value if current node is array type.

Usage:

Example
 1	root := Must(Unmarshal([]byte(`["foo", 1]`)))
 2	arr, err := root.GetArray()
 3	if err != nil {
 4		t.Errorf("GetArray returns error: %v", err)
 5	}
 6
 7	for _, val := range arr {
 8		println(val)
 9	}
10
11 result: "foo", 1

func GetBool

method on Node
1func (n *Node) GetBool() (bool, error)
source

GetBool returns the boolean value if current node is boolean type.

Usage:

Example
1root := Unmarshal([]byte("true"))
2val, err := root.GetBool()
3if err != nil {
4	t.Errorf("GetBool returns error: %v", err)
5}
6println(val) // true

func GetIndex

method on Node
1func (n *Node) GetIndex(idx int) (*Node, error)
source

GetIndex returns the array element at the given index.

if the index is negative, it returns the index is from the end of the array.

func GetKey

method on Node
1func (n *Node) GetKey(key string) (*Node, error)
source

GetKey returns the value of the given key from the current object node.

func GetNull

method on Node
1func (n *Node) GetNull() (any, error)
source

GetNull returns the null value if current node is null type.

Usage:

Example
1root := Unmarshal([]byte("null"))
2val, err := root.GetNull()
3if err != nil {
4	t.Errorf("GetNull returns error: %v", err)
5}
6if val != nil {
7	t.Errorf("GetNull returns wrong result: %v", val)
8}

func GetNumeric

method on Node
1func (n *Node) GetNumeric() (float64, error)
source

GetNumeric returns the numeric (int/float) value if current node is number type.

Usage:

Example
1root := Unmarshal([]byte("10.5"))
2val, err := root.GetNumeric()
3if err != nil {
4	t.Errorf("GetNumeric returns error: %v", err)
5}
6println(val) // 10.5

func GetObject

method on Node
1func (n *Node) GetObject() (map[string]*Node, error)
source

GetObject returns the object value if current node is object type.

Usage:

Example
1root := Must(Unmarshal([]byte(`{"key": "value"}`)))
2obj, err := root.GetObject()
3if err != nil {
4	t.Errorf("GetObject returns error: %v", err)
5}
6
7result: map[string]*Node{"key": StringNode("key", "value")}

func GetString

method on Node
1func (n *Node) GetString() (string, error)
source

GetString returns the string value if current node is string type.

Usage:

Example
 1root, err := Unmarshal([]byte("foo"))
 2if err != nil {
 3	t.Errorf("Error on Unmarshal(): %s", err)
 4}
 5
 6str, err := root.GetString()
 7if err != nil {
 8	t.Errorf("should retrieve string value: %s", err)
 9}
10
11println(str) // "foo"

func HasKey

method on Node
1func (n *Node) HasKey(key string) bool
source

HasKey checks the current node has the given key or not.

func Index

method on Node
1func (n *Node) Index() int
source

Index returns the index of the current node in the parent array node.

Usage:

Example
1root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
2if root == nil {
3	t.Errorf("ArrayNode returns nil")
4}
5
6if root.MustIndex(1).Index() != 1 {
7	t.Errorf("Index returns wrong index: %d", root.MustIndex(1).Index())
8}

We can also use the index to the byte slice of the JSON data directly.

Example:

Example
1root := Unmarshal([]byte(`["foo", 1]`))
2if root == nil {
3	t.Errorf("Unmarshal returns nil")
4}
5
6if string(root.MustIndex(1).source()) != "1" {
7	t.Errorf("source returns wrong result: %s", root.MustIndex(1).source())
8}

func IsArray

method on Node
1func (n *Node) IsArray() bool
source

IsArray returns true if the current node is array type.

func IsBool

method on Node
1func (n *Node) IsBool() bool
source

IsBool returns true if the current node is boolean type.

func IsNull

method on Node
1func (n *Node) IsNull() bool
source

IsNull returns true if the current node is null type.

func IsNumber

method on Node
1func (n *Node) IsNumber() bool
source

IsNumber returns true if the current node is number type.

func IsObject

method on Node
1func (n *Node) IsObject() bool
source

IsObject returns true if the current node is object type.

func IsString

method on Node
1func (n *Node) IsString() bool
source

IsString returns true if the current node is string type.

func Key

method on Node
1func (n *Node) Key() string
source

Key returns the key of the current node.

func MustArray

method on Node
1func (n *Node) MustArray() []*Node
source

MustArray returns the array value if current node is array type.

It panics if the current node is not array type.

func MustBool

method on Node
1func (n *Node) MustBool() bool
source

MustBool returns the boolean value if current node is boolean type.

It panics if the current node is not boolean type.

func MustIndex

method on Node
1func (n *Node) MustIndex(expectIdx int) *Node
source

MustIndex returns the array element at the given index.

If the index is negative, it returns the index is from the end of the array. Also, it panics if the index is not found.

check the Index method for detailed usage.

func MustKey

method on Node
1func (n *Node) MustKey(key string) *Node
source

MustKey returns the value of the given key from the current object node.

func MustNull

method on Node
1func (n *Node) MustNull() any
source

MustNull returns the null value if current node is null type.

It panics if the current node is not null type.

func MustNumeric

method on Node
1func (n *Node) MustNumeric() float64
source

MustNumeric returns the numeric (int/float) value if current node is number type.

It panics if the current node is not number type.

func MustObject

method on Node
1func (n *Node) MustObject() map[string]*Node
source

MustObject returns the object value if current node is object type.

It panics if the current node is not object type.

func MustString

method on Node
1func (n *Node) MustString() string
source

MustString returns the string value if current node is string type.

It panics if the current node is not string type.

func ObjectEach

method on Node
1func (n *Node) ObjectEach(callback func(key string, value *Node))
source

ObjectEach executes the callback for each key-value pair in the JSON object.

Usage:

Example
1jsonObjectNode.ObjectEach(func(key string, valueNode *Node) {
2    ufmt.Println(key, valueNode)
3})

func Path

method on Node
1func (n *Node) Path() string
source

Path builds the path of the current node.

For example:

Example
1{ "key": { "sub": [ "val1", "val2" ] }}

The path of "val2" is: $.key.sub[1]

func Size

method on Node
1func (n *Node) Size() int
source

Size returns the size (length) of the current array node.

Usage:

Example
1root := ArrayNode("", []*Node{StringNode("", "foo"), NumberNode("", 1)})
2if root == nil {
3	t.Errorf("ArrayNode returns nil")
4}
5
6if root.Size() != 2 {
7	t.Errorf("ArrayNode returns wrong size: %d", root.Size())
8}

func String

method on Node
1func (n *Node) String() string
source

String converts the node to a string representation.

func Type

method on Node
1func (n *Node) Type() ValueType
source

Type returns the type (ValueType) of the current node.

func UniqueKeyLists

method on Node
1func (n *Node) UniqueKeyLists() []string
source

UniqueKeyLists traverses the current JSON nodes and collects all the unique keys.

func Value

method on Node
1func (n *Node) Value() (value any, err error)
source

Value returns the value of the current node.

Usage:

Example
1root := Unmarshal([]byte(`{"key": "value"}`))
2val, err := root.MustKey("key").Value()
3if err != nil {
4	t.Errorf("Value returns error: %v", err)
5}
6
7result: "value"

type NodeBuilder

struct
1type NodeBuilder struct {
2	node *Node
3}
source

Methods on NodeBuilder

func Node

method on NodeBuilder
1func (b *NodeBuilder) Node() *Node
source

func WriteArray

method on NodeBuilder
1func (b *NodeBuilder) WriteArray(key string, fn func(*ArrayBuilder)) *NodeBuilder
source

func WriteBool

method on NodeBuilder
1func (b *NodeBuilder) WriteBool(key string, value bool) *NodeBuilder
source

func WriteNull

method on NodeBuilder
1func (b *NodeBuilder) WriteNull(key string) *NodeBuilder
source

func WriteNumber

method on NodeBuilder
1func (b *NodeBuilder) WriteNumber(key string, value float64) *NodeBuilder
source

func WriteObject

method on NodeBuilder
1func (b *NodeBuilder) WriteObject(key string, fn func(*NodeBuilder)) *NodeBuilder
source

func WriteString

method on NodeBuilder
1func (b *NodeBuilder) WriteString(key, value string) *NodeBuilder
source

type ValueType

ident
1type ValueType int
source

Methods on ValueType

func String

method on ValueType
1func (v ValueType) String() string
source

Imports 7

Source Files 24