jsonz

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: MIT Imports: 7 Imported by: 0

README

gopherz

ezpkg.io/jsonz

PkgGoDev GitHub License version

Package jsonz is a minimal implementation of json parser and transformer in Go. The

Installation

go get -u ezpkg.io/jsonz@v0.2.0

Parse() function returns an iter over the JSON object, which can be used to traverse the JSON object.

Examples

1. Iterate over the JSON object:
package main

import (
	"fmt"
	"ezpkg.io/jsonz"
)

func main() {
	jsonStr := `{"name": "Alice", "age": 24, "address": {"city": "The Sun", "zip": 10101}}`

	fmt.Println("| Path | Index | Key | Token |")
	fmt.Println("|------|-------|-----|-------|")
	for item, err := range jsonz.Parse([]byte(jsonStr)) {
		if err != nil {
			panic(err)
		}
		fmt.Printf("| %v | %v | %v | %v |\n", item.GetPath(), item.Index, item.Key, item.Token)
	}
}

Will output:

Path Index Key Token
0 {
name 0 "name" "Alice"
age 1 "age" 24
scores 2 "scores" [
scores.0 0 9
scores.1 1 10
scores.2 2 8
scores 2 ]
address 3 "address" {
address.city 0 "city" "The Sun"
address.zip 1 "zip" 10101
address 3 }
0 }
2. Reconstruction of the JSON object:

You can reconstruct the JSON object by iterating over the JSON object and adding commas between the tokens. This is useful when you want to modify the JSON object and write it back to a file.

package main

import (
	"bytes"
	"fmt"
	"ezpkg.io/jsonz"
)

func main() {
	jsonStr := `{"name": "Alice", "age": 24, "address": {"city": "The Sun", "zip": 10101}}`
	
	var b bytes.Buffer
	var lastTokenType jsonz.TokenType
	for item, err := range jsonz.Parse([]byte(jsonStr)) {
		if err != nil {
			panic(err)
		}
		if jsonz.ShouldAddComma(lastTokenType, item.Token.Type()) {
			b.WriteByte(',')
		}
		if item.Key.IsValue() {
			b.Write(item.Key.Raw())
			b.WriteByte(':')
		}
		b.Write(item.Token.Raw())
		lastTokenType = item.Token.Type()
	}
	fmt.Printf("%s\n", b.Bytes())
}

Will output:

{"name":"Alice","age":24,"scores":[9,10,8],"address":{"city":"The Sun","zip":10101}}
3. Reformat the JSON object:

This example will reformat the JSON object by adding newlines and indentation.

package main

import (
	"fmt"
	"ezpkg.io/jsonz"
	"ezpkg.io/bytez"
)

func main() {
	jsonStr := `{"name": "Alice", "age": 24, "address": {"city": "The Sun", "zip": 10101}}`
	
	var b bytez.Buffer
	var lastTokenType jsonz.TokenType
	for item, err := range jsonz.Parse([]byte(jsonStr)) {
		if err != nil {
			panic(err)
		}
		if jsonz.ShouldAddComma(lastTokenType, item.Token.Type()) {
			b.Print(",")
		}
		b.Println()
		for i := 0; i < item.Level; i++ {
			b.Print("  ")
		}
		if item.Key.IsValue() {
			b.WriteZ(item.Key.Raw())
			b.Print(": ")
		}
		b.WriteZ(item.Token.Raw())
		lastTokenType = item.Token.Type()
	}
	fmt.Printf("%s\n", b.Bytes())
}

Will output:

{
  "name": "Alice",
  "age": 24,
  "scores": [
	9,
	10,
	8
  ],
  "address": {
	"city": "The Sun",
	"zip": 10101
  }
}

About ezpkg.io

As I work on various Go projects, I often find myself creating utility functions, extending existing packages, or developing packages to solve specific problems. Moving from one project to another, I usually have to copy or rewrite these solutions. So I created this repository to have all these utilities and packages in one place. Hopefully, you'll find them useful as well.

For more information, see the main repository.

Author

Oliver Nguyen  github

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(in []byte) iter.Seq2[Item, error]

func Reconstruct

func Reconstruct(in []byte) ([]byte, error)

Reconstruct is an example of how to reconstruct a JSON from Parse().

func Scan

func Scan(in []byte) iter.Seq2[RawToken, error]

func ShouldAddComma

func ShouldAddComma(lastToken, nextToken TokenType) bool

Types

type Item

type Item struct {
	Level int      // level of indentation
	Index int      // index in the parent array or object
	Key   RawToken // optional object "key"
	Token RawToken // [ or { or } or ] or , or value
	// contains filtered or unexported fields
}

func (Item) Format

func (x Item) Format(f fmt.State, c rune)

func (Item) GetAltPathString

func (x Item) GetAltPathString() string

GetAltPathString returns the path of the item as a string `[0].key[1]`.

func (Item) GetPath

func (x Item) GetPath() Path

GetPath returns the path of the item as a slice of values. The values are the keys of objects (string) and the indexes of arrays (int).

func (Item) GetPathString

func (x Item) GetPathString() string

GetPathString returns the path of the item as a string "0.key.1".

func (Item) GetRawPath

func (x Item) GetRawPath() RawPath

GetRawPath returns the path of the item as a slice of PathItem. IMPORTANT: The result slice should not be modified.

func (Item) GetTokenValue

func (x Item) GetTokenValue() (any, error)

func (Item) GetValue

func (x Item) GetValue() (any, error)

func (Item) IsArrayValue

func (x Item) IsArrayValue() bool

func (Item) IsObjectValue

func (x Item) IsObjectValue() bool

func (Item) String

func (x Item) String() string

type Path

type Path []any

Path is a slice of values. The values are the keys of objects (string) and the indexes of arrays (int).

func (Path) Format

func (p Path) Format(f fmt.State, c rune)

Path returns the path of the item as a string. Default to 0.key.1 or "%+v" to format as [0]."key"[1]

func (Path) String

func (p Path) String() string

Path returns the path of the item as a string. Default to 0.key.1 or "%+v" to format as [0]."key"[1]

type PathItem

type PathItem struct {
	Index int
	Token RawToken
	Key   RawToken
}

func (PathItem) Format

func (p PathItem) Format(f fmt.State, c rune)

Format formats the path item as a string. Use "%+v" to format as "[0]" for array, ".key" for object.

func (PathItem) IsArray

func (p PathItem) IsArray() bool

IsArray returns true if the path item is inside an array.

func (PathItem) IsObject

func (p PathItem) IsObject() bool

IsObject returns true if the path item is inside an object.

func (PathItem) String

func (p PathItem) String() string

String returns the string representation of the path item. "0" for array, "key" for object.

func (PathItem) Value

func (p PathItem) Value() any

Value returns the value of the path item. If the item is inside an array, it returns the index. If the item is inside an object, it returns the key.

type RawPath

type RawPath []PathItem

func (RawPath) Format

func (p RawPath) Format(f fmt.State, c rune)

Format formats the path as a string. Default to 0.key.1 or "%+v" to format as [0]."key"[1]

func (RawPath) String

func (p RawPath) String() string

String returns the path of the item as a string. Default to 0.key.1 or "%+v" to format as [0]."key"[1]

type RawToken

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

RawToken represents a raw token from the scanner.

func NextToken

func NextToken(in []byte) (token RawToken, remain []byte, err error)

func (RawToken) Bytes

func (r RawToken) Bytes() []byte

Bytes returns the raw bytes value of the token.

func (RawToken) GetBool

func (r RawToken) GetBool() (bool, error)

GetBool returns the boolean value of the token.

func (RawToken) GetNumber

func (r RawToken) GetNumber() (float64, error)

GetNumber returns the number value of the token.

func (RawToken) GetString

func (r RawToken) GetString() (string, error)

GetString returns the unquoted string value of the token. https://datatracker.ietf.org/doc/html/rfc8259#section-7

func (RawToken) GetValue

func (r RawToken) GetValue() (any, error)

GetValue returns the value of the token as an any.

func (RawToken) IsClose

func (r RawToken) IsClose() bool

IsClose returns true if the token is a close token ']' or '}'.

func (RawToken) IsOpen

func (r RawToken) IsOpen() bool

IsOpen returns true if the token is an open token '[' or '{'.

func (RawToken) IsValue

func (r RawToken) IsValue() bool

IsValue returns true if the token is a value.

func (RawToken) IsZero

func (r RawToken) IsZero() bool

IsZero returns true if the token is zero.

func (RawToken) Raw

func (r RawToken) Raw() []byte

Raw returns the raw bytes value of the token.

func (RawToken) String

func (r RawToken) String() string

String returns the raw string value of the token. Use ToString() for unquoted strings.

func (RawToken) Type

func (r RawToken) Type() TokenType

Type returns the type of the token.

type TokenType

type TokenType byte

TokenType represents the type of a JSON token.

const (
	TokenNull        TokenType = 'n'
	TokenTrue        TokenType = 't'
	TokenFalse       TokenType = 'f'
	TokenNumber      TokenType = '0'
	TokenString      TokenType = '"'
	TokenObjectStart TokenType = '{'
	TokenObjectEnd   TokenType = '}'
	TokenArrayStart  TokenType = '['
	TokenArrayEnd    TokenType = ']'
	TokenComma       TokenType = ','
	TokenColon       TokenType = ':'
)

func (TokenType) String

func (t TokenType) String() string

Jump to

Keyboard shortcuts

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