gjson

package module
v0.0.0-...-1f68efa Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2020 License: MIT Imports: 6 Imported by: 11

README

gjson

gjson provides a convenient way to read arbitrary JSON in Go.

Build codecov Go Report Card GoDoc License

Install

go get -u github.com/winterssy/gjson

Usage

import "github.com/winterssy/gjson"

Quick Start

  • Parse to gjson.Object
data, err := ioutil.ReadFile("./testdata/music.json")
if err != nil {
    log.Fatal(err)
}

obj, err := gjson.Parse(data)
if err != nil {
    panic(err)
}

fmt.Println(obj.GetNumber("code"))
fmt.Println(obj.GetString("data", "total"))
fmt.Println(obj.GetArray("data", "list").Index(0).ToObject().GetString("name"))
// Output:
// 200
// 1917
// 告白气球
  • Bind to struct
const dummyData = `
{
  "code": 200,
  "data": {
    "list": [
      {
        "artist": "周杰伦",
        "album": "周杰伦的床边故事",
        "name": "告白气球"
      },
      {
        "artist": "周杰伦",
        "album": "说好不哭 (with 五月天阿信)",
        "name": "说好不哭 (with 五月天阿信)"
      }
    ]
  }
}
`
var s struct {
    Code int `json:"code"`
    Data struct {
        List gjson.Array `json:"list"`
    } `json:"data"`
}
err := gjson.UnmarshalFromString(dummyData, &s)
if err != nil {
    panic(err)
}

fmt.Println(s.Data.List.Index(0).ToObject().GetString("name"))
// Output:
// 告白气球

Build with jsoniter

gjson uses encoding/json as default json package but you can change to jsoniter by build from other tags.

go build -tags=jsoniter .

License

MIT

Documentation

Overview

Example (BindToStruct)
package main

import (
	"fmt"

	"github.com/winterssy/gjson"
)

func main() {
	const dummyData = `
{
  "code": 200,
  "data": {
    "list": [
      {
        "artist": "周杰伦",
        "album": "周杰伦的床边故事",
        "name": "告白气球"
      },
      {
        "artist": "周杰伦",
        "album": "说好不哭 (with 五月天阿信)",
        "name": "说好不哭 (with 五月天阿信)"
      }
    ]
  }
}
`
	var s struct {
		Code int `json:"code"`
		Data struct {
			List gjson.Array `json:"list"`
		} `json:"data"`
	}
	err := gjson.UnmarshalFromString(dummyData, &s)
	if err != nil {
		panic(err)
	}

	fmt.Println(s.Data.List.Index(0).ToObject().GetString("name"))
}
Output:

告白气球
Example (ParseToObject)
package main

import (
	"fmt"
	"io/ioutil"
	"log"

	"github.com/winterssy/gjson"
)

func main() {
	data, err := ioutil.ReadFile("./testdata/music.json")
	if err != nil {
		log.Fatal(err)
	}

	obj, err := gjson.Parse(data)
	if err != nil {
		panic(err)
	}

	fmt.Println(obj.GetNumber("code"))
	fmt.Println(obj.GetString("data", "total"))
	fmt.Println(obj.GetArray("data", "list").Index(0).ToObject().GetString("name"))
}
Output:

200
1917
告白气球

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	Marshal       = json.Marshal
	MarshalIndent = json.MarshalIndent
	Unmarshal     = json.Unmarshal
)

Methods from encoding/json or jsoniter.

Functions

func Decode

func Decode(data []byte, v interface{}, opts ...func(dec *Decoder)) error

Decode is like Unmarshal, but it uses a decoder instead of an unmarshaler.

func DecodeFromString

func DecodeFromString(s string, v interface{}, opts ...func(dec *Decoder)) error

DecodeFromString is like Decode, but it reads from string instead of []byte.

func Encode

func Encode(v interface{}, opts ...func(enc *Encoder)) ([]byte, error)

Encode is like Marshal, but it uses a encoder instead of a marshaler.

func EncodeToString

func EncodeToString(v interface{}, opts ...func(enc *Encoder)) (string, error)

EncodeToString is like Encode, but it returns the string instead of []byte.

func MarshalIndentToString

func MarshalIndentToString(v interface{}, prefix, indent string) (string, error)

MarshalIndentToString is like MarshalIndent, but it returns the string instead of []byte.

func MarshalToString

func MarshalToString(v interface{}) (string, error)

MarshalToString is like Marshal, but it returns the string instead of []byte.

func UnmarshalFromString

func UnmarshalFromString(s string, v interface{}) error

UnmarshalFromString is like Unmarshal, but it reads from string instead of []byte.

Types

type Any

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

Any is a wrapper around an interface{}, represents any JSON value.

func (*Any) Interface

func (v *Any) Interface() interface{}

Interface returns the original data of v or nil if v is nil.

func (*Any) IsNull

func (v *Any) IsNull() bool

IsNull reports whether the original data of v is null or not. Note: if v is nil, it returns false.

func (*Any) MarshalJSON

func (v *Any) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*Any) ToArray

func (v *Any) ToArray() Array

ToArray casts v to an Array. If v is nil or the data type doesn't match, it will return the zero value.

func (*Any) ToBoolean

func (v *Any) ToBoolean() bool

ToBoolean casts v to a bool. If v is nil or the data type doesn't match, it will return the zero value.

func (*Any) ToNumber

func (v *Any) ToNumber() Number

ToNumber casts v to a Number. If v is nil or the data type doesn't match, it will return the zero value.

func (*Any) ToObject

func (v *Any) ToObject() Object

ToObject casts v to an Object. If v is nil or the data type doesn't match, it will return the zero value.

func (*Any) ToString

func (v *Any) ToString() string

ToString casts v to a string. If v is nil or the data type doesn't match, it will return the zero value.

func (*Any) UnmarshalJSON

func (v *Any) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type Array

type Array []*Any

Array is a shortcut for []*Any, represents JSON arrays.

func (Array) Filter

func (arr Array) Filter(selector func(index int, value *Any) bool) Array

Filter returns the elements of arr that match selector.

func (Array) Index

func (arr Array) Index(i int) *Any

Index provides an elegant way to get arr's i'th element without panic even index out of range.

func (Array) Size

func (arr Array) Size() int

Size returns the length of arr.

func (Array) ToBooleans

func (arr Array) ToBooleans() []bool

ToBooleans casts arr to a bool array.

func (Array) ToNumbers

func (arr Array) ToNumbers() []Number

ToNumbers casts arr to a Number array.

func (Array) ToObjects

func (arr Array) ToObjects() []Object

ToObjects casts arr to an Object array.

func (Array) ToStrings

func (arr Array) ToStrings() []string

ToStrings casts arr to a string array.

type Decoder

type Decoder = json.Decoder

Decoder is an alias of json.Decoder or jsoniter.Decoder.

func NewDecoder

func NewDecoder(r io.Reader, opts ...func(dec *Decoder)) *Decoder

NewDecoder returns a new decoder that reads from r.

type Encoder

type Encoder = json.Encoder

Encoder is an alias of json.Encoder or jsoniter.Encoder.

func NewEncoder

func NewEncoder(w io.Writer, opts ...func(enc *Encoder)) *Encoder

NewEncoder returns a new encoder that writes to w.

type Number

type Number float64

Number is a shortcut for float64, represents JSON numbers.

func (Number) ToFloat32

func (n Number) ToFloat32() float32

ToFloat32 casts n to a float32.

func (Number) ToFloat64

func (n Number) ToFloat64() float64

ToFloat64 casts n to a float64.

func (Number) ToInt

func (n Number) ToInt() int

ToInt casts n to an int.

func (Number) ToInt16

func (n Number) ToInt16() int16

ToInt16 casts n to an int16.

func (Number) ToInt32

func (n Number) ToInt32() int32

ToInt32 casts n to an int32.

func (Number) ToInt64

func (n Number) ToInt64() int64

ToInt64 casts n to an int64.

func (Number) ToInt8

func (n Number) ToInt8() int8

ToInt8 casts n to an int8.

func (Number) ToString

func (n Number) ToString() string

ToString casts n to a string.

func (Number) ToUint

func (n Number) ToUint() uint

ToUint casts n to a uint.

func (Number) ToUint16

func (n Number) ToUint16() uint16

ToUint16 casts n to a uint16.

func (Number) ToUint32

func (n Number) ToUint32() uint32

ToUint32 casts n to a uint32.

func (Number) ToUint64

func (n Number) ToUint64() uint64

ToUint64 casts n to a uint64.

func (Number) ToUint8

func (n Number) ToUint8() uint8

ToUint8 casts n to a uint8.

type Object

type Object map[string]interface{}

Object is a shortcut for map[string]interface{}, represents JSON objects.

func Parse

func Parse(data []byte) (obj Object, err error)

Parse parses the JSON-encoded data and stores the result in an Object.

func ParseFromReader

func ParseFromReader(r io.Reader, opts ...func(dec *Decoder)) (obj Object, err error)

ParseFromReader reads the next JSON-encoded value from its input and stores it in an Object.

func ParseFromString

func ParseFromString(s string) (obj Object, err error)

ParseFromString is like Parse, but it reads from string instead of []byte.

func (Object) GetAny

func (obj Object) GetAny(key string, childNodes ...string) *Any

GetAny gets any value associated with key recursively. If the key not exists, it returns nil.

func (Object) GetArray

func (obj Object) GetArray(key string, childNodes ...string) Array

GetArray gets array value associated with key recursively. If the key not exists, it returns the zero value.

func (Object) GetBoolean

func (obj Object) GetBoolean(key string, childNodes ...string) bool

GetBoolean gets boolean value associated with key recursively. If the key not exists, it returns the zero value.

func (Object) GetNumber

func (obj Object) GetNumber(key string, childNodes ...string) Number

GetNumber gets number value associated with key recursively. If the key not exists, it returns the zero value.

func (Object) GetObject

func (obj Object) GetObject(key string, childNodes ...string) Object

GetObject gets object value associated with key recursively. If the key not exists, it returns the zero value.

func (Object) GetString

func (obj Object) GetString(key string, childNodes ...string) string

GetString gets string value associated with key recursively. If the key not exists, it returns the zero value.

func (Object) String

func (obj Object) String() string

String implements fmt.Stringer interface, it returns the pretty JSON encoding of obj.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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