jsonport

package module
v0.0.0-...-139b207 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2020 License: MIT Imports: 11 Imported by: 2

README

jsonport GoDoc

jsonport is a simple and high performance golang package for accessing json without pain. features:

  • No reflection.
  • Unmarshal without struct.
  • Unmarshal for the given json path only.
  • 2x faster than encoding/json.

It is inspired by jmoiron/jsonq. Feel free to post issues or PRs, I will reply ASAP :-)

Usage

package main

import (
	"fmt"

	"github.com/xiaost/jsonport"
)

func main() {
	jsonstr := `{
		"timestamp": "1438194274",
		"users": [{"id": 1, "name": "Tom"}, {"id": 2, "name": "Peter"}],
		"keywords": ["golang", "json"],
		"status": 1
	}`
	j, _ := jsonport.Unmarshal([]byte(jsonstr))

	fmt.Println(j.GetString("users", 0, "name"))             // Tom, nil
	fmt.Println(j.Get("keywords").StringArray())             // [golang json], nil
	fmt.Println(j.Get("users").EachOf("name").StringArray()) // [Tom Peter],  nil

	// try parse STRING as NUMBER
	fmt.Println(j.Get("timestamp").Int()) // 0, type mismatch: expected NUMBER, found STRING
	j.StringAsNumber()
	fmt.Println(j.Get("timestamp").Int()) // 1438194274, nil

	// convert NUMBER, STRING, ARRAY and OBJECT type to BOOL
	fmt.Println(j.GetBool("status")) // false, type mismatch: expected BOOL, found NUMBER
	j.AllAsBool()
	fmt.Println(j.GetBool("status")) // true, nil

	// using Unmarshal with path which can speed up json decode
	j, _ = jsonport.Unmarshal([]byte(jsonstr), "users", 1, "name")
	fmt.Println(j.String()) // Peter, nil
}

For more information on getting started with jsonport check out the doc

Documentation

Overview

Example (Usage)
jsonstr := `{
		"timestamp": "1438194274",
		"users": [{"id": 1, "name": "Tom"}, {"id": 2, "name": "Peter"}],
		"keywords": ["golang", "json"]
	}`
j, _ := Unmarshal([]byte(jsonstr))

// Output: Tom
fmt.Println(j.GetString("users", 0, "name"))

// Output: [golang json]
fmt.Println(j.Get("keywords").StringArray())

// Output: [Tom Peter]
names, _ := j.Get("users").EachOf("name").StringArray()
fmt.Println(names)

// try parse STRING as NUMBER
j.StringAsNumber()
// Output: 1438194274
fmt.Println(j.Get("timestamp").Int())

// convert NUMBER, STRING, ARRAY and OBJECT type to BOOL
j.AllAsBool()
// Output: false
fmt.Println(j.GetBool("status"))

// using Unmarshal with path which can speed up json decode
j, _ = Unmarshal([]byte(jsonstr), "users", 1, "name")
fmt.Println(j.String())
Output:

Tom <nil>
[golang json] <nil>
[Tom Peter]
1438194274 <nil>
false <nil>
Peter <nil>

Index

Examples

Constants

View Source
const (
	ParseMemberNamesOnly = "__member_names_only__"
)

Variables

View Source
var (
	ErrMoreBytes = errors.New("not all bytes unmarshaled")
)

Functions

This section is empty.

Types

type Json

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

Json represents everything of json

func DecodeFrom

func DecodeFrom(r io.Reader) (Json, error)

DecodeFrom parses data from reader to json

func Unmarshal

func Unmarshal(data []byte, keys ...interface{}) (Json, error)

Unmarshal parses data to Json. When specified keys, jsonport skips unused field for performance

func (*Json) AllAsBool

func (j *Json) AllAsBool()

AllAsBool enables conversion of Bool():

STRING, ARRAY, OBJECT:	true if Len() != 0
NUMBER:	true if Float() != 0
NULL:	false
Example
jsonstr := `{"enabled": 1}`
j, _ := Unmarshal([]byte(jsonstr))

fmt.Println("Without AllAsBool():")
b, err := j.GetBool("enabled")
fmt.Println(b, err)

fmt.Println("With AllAsBool():")
j.AllAsBool()
b, err = j.GetBool("enabled")
fmt.Println(b, err)
Output:

Without AllAsBool():
false type mismatch: expected BOOL, found NUMBER
With AllAsBool():
true <nil>

func (Json) Array

func (j Json) Array() ([]Json, error)

Array converts current json value to []Json. error is returned if value type not equal to ARRAY.

func (Json) Bool

func (j Json) Bool() (bool, error)

Bool converts current json value to bool

func (Json) BoolArray

func (j Json) BoolArray() ([]bool, error)

BoolArray converts current json value to []bool. error is returned if any element type not equal to NUMBER.

func (Json) EachOf

func (j Json) EachOf(keys ...interface{}) Json

EachOf convert every elements specified by keys in json value to ARRAY. Json.Error() is set if an error occurred. it is equal to `Json{[e.Get(keys...) for e in j.Array()]}`

func (Json) Element

func (j Json) Element(i int) Json

Element returns the (i+1)th element of array. a NULL type Json is returned if index out of range. Json.Error() is set if type not equal to ARRAY.

func (Json) Error

func (j Json) Error() error

Error returns error of current context

func (Json) Float

func (j Json) Float() (float64, error)

Float converts current json value to float64

func (Json) FloatArray

func (j Json) FloatArray() ([]float64, error)

FloatArray converts current json value to []float64. error is returned if any element type not equal to NUMBER.

func (Json) Get

func (j Json) Get(keys ...interface{}) Json

Get returns Json object by key sequence.

key with the type of string is equal to j.Member(k),
key with the type of number is equal to j.Element(k),
j.Get("key", 1) is equal to j.Member("key").Element(1).

a NULL type Json returned with err if:

  • key type not supported. (neither number nor string)
  • json value type mismatch.

func (Json) GetBool

func (j Json) GetBool(keys ...interface{}) (bool, error)

GetBool convert json value specified by keys to bool, it is equal to Get(keys...).Bool()

func (Json) GetFloat

func (j Json) GetFloat(keys ...interface{}) (float64, error)

GetFloat convert json value specified by keys to float64, it is equal to Get(keys...).Float()

func (Json) GetInt

func (j Json) GetInt(keys ...interface{}) (int64, error)

GetInt convert json value specified by keys to int64, it is equal to Get(keys...).Int()

func (Json) GetString

func (j Json) GetString(keys ...interface{}) (string, error)

GetString convert json value specified by keys to string, it is equal to Get(keys...).String()

func (Json) Int

func (j Json) Int() (int64, error)

Int converts current json value to int64 result will be negative if pasring from uint64 like `1<<63`

func (Json) IntArray

func (j Json) IntArray() ([]int64, error)

IntArray converts current json value to []int64. error is returned if any element type not equal to NUMBER.

func (Json) IsArray

func (j Json) IsArray() bool

func (Json) IsBool

func (j Json) IsBool() bool

func (Json) IsNull

func (j Json) IsNull() bool

func (Json) IsNumber

func (j Json) IsNumber() bool

func (Json) IsObject

func (j Json) IsObject() bool

func (Json) IsString

func (j Json) IsString() bool

func (Json) Keys

func (j Json) Keys() ([]string, error)

Keys returns the field names of json object. error is returned if value type not equal to OBJECT.

func (Json) Len

func (j Json) Len() (int, error)

Len returns the length of json value.

STRING:	the number of bytes
ARRAY:	the number of elements
OBJECT:	the number of pairs

func (Json) Member

func (j Json) Member(name string) Json

Member returns the member value specified by `name` a NULL type Json is returned if member not found Json.Error() is set if type not equal to OBJECT

func (Json) String

func (j Json) String() (string, error)

String converts current json value to string

func (Json) StringArray

func (j Json) StringArray() ([]string, error)

StringArray converts current json value to []string. error is returned if any element type not equal to STRING.

func (*Json) StringAsNumber

func (j *Json) StringAsNumber()

StringAsNumber enables conversion like {"id": "123"}, j.GetInt("id") is returned 123 instead of an err, j.GetString("id") is returned "123" as expected.

Example
jsonstr := `{"timestamp": "1438194274"}`
j, _ := Unmarshal([]byte(jsonstr))

fmt.Println("Without StringAsNumber():")
n, err := j.GetInt("timestamp")
fmt.Println(n, err)

fmt.Println("With StringAsNumber():")
j.StringAsNumber()
n, err = j.GetInt("timestamp")
fmt.Println(n, err)
Output:

Without StringAsNumber():
0 type mismatch: expected NUMBER, found STRING
With StringAsNumber():
1438194274 <nil>

func (Json) Type

func (j Json) Type() Type

Type returns the Type of current json value

func (Json) Values

func (j Json) Values() ([]Json, error)

Values returns the field values of json object. error is returned if value type not equal to OBJECT.

type Number

type Number string

A Number represents a JSON number literal.

func (Number) Float64

func (n Number) Float64() (float64, error)

Float64 returns the number as a float64.

func (Number) Int64

func (n Number) Int64() (int64, error)

Int64 returns the number as an int64.

func (Number) String

func (n Number) String() string

String returns the literal text of the number.

type Type

type Type int
const (
	INVALID Type = iota
	OBJECT
	ARRAY
	STRING
	NUMBER
	BOOL
	NULL
)

func (Type) String

func (t Type) String() string

Jump to

Keyboard shortcuts

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