jsoncrack

package module
v0.0.0-...-f4ccba1 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2019 License: Apache-2.0 Imports: 7 Imported by: 4

README

jsoncrack

Godoc Build Status

jsoncrack is tool on developing to operate json []byte straightly.

Table of Contents generated with DocToc

1. Start

go get github.com/fwhezfwhez/jsoncrack

2. Notice

2.1 json marshaller can be specific when inited.

Any instance that realize JsonMarshaller interface can be set jsoncrack's json marshaller. The default is the official json package encoding/json.

type JsonMarshaller interface {
    Marshal(interface{}) ([]byte, error)
    Unmarshal([]byte, interface{}) error
}

type Jsoner struct {
}

func (j Jsoner) Marshal(dest interface{}) ([]byte, error) {
    return json.Marshal(dest)
}

func (j Jsoner) Unmarshal(data []byte, dest interface{}) error {
    return json.Unmarshal(data, dest)
}
func main() {
    jsonMarshaler := Jsoner{}
    jc := jsoncrack.NewCracker(jsonMarshaler)
    ....
}

2.2 crud of jsoncrack doesn't change the original data.

All apis of jsoncrack which operates []byte data returns a modified copy of the original data.

2.3 Get() and Delete() can specific the returning type of the modified copy of data,ranging in [jsoncrack.MAP, jsoncrack.ARRAY, jsoncrack.BYTE]

jsoncrack.Bytes is ok for all cases.If you ensure your returning data is a formated map[string]interface{}, json.Map is optional. jsoncrack.ARRAY is now the same as BYTES.It might be changed with upgrading the version of jsoncrack.

3. Function menus

function info
Marshal json encoding
Unmarshal json decoding
Update update json []byte field
Delete delete json []byte field
Add add json []byte field
Get get json []byte field value

4. Example

package main

import (
    "fmt"
    "jsoncrack"
)

func main() {
    var in = []byte(`{
        "class": {
            "name": "高中1班",
            "master": {
                "name": "张一山",
                "age": 21,
                "company": {
                    "name": "go公司",
                    "built_by": "张二山",
                    "manager": ["张一山", "张二山", "张三山"],
                    "country": {
                        "name": "China",
                        "location": "Asure"
                    }
                }
            }
        }
    }`)

    // init
    jc := jsoncrack.NewCracker(nil)
    // get
    fmt.Println("get class.master")
    r ,e :=jc.Get(jsoncrack.BYTES, in, "class", "master")
    if e!=nil {
        panic(e)
    }
    fmt.Println(string(r.([]byte)))

    // update
    fmt.Println("update class.master.company.country.location")
    r, e = jc.Update(in, "location", "亚洲", "class", "master", "company", "country")
    if e!=nil {
        panic(e)
    }
    fmt.Println(string(r.([]byte)))

    // add
    fmt.Println("add class.master.company.country.chinese_name : '中国'")
    r, e = jc.Add(in, "chinese_name", "中国", "class", "master", "company", "country")
    if e!=nil {
        panic(e)
    }
    fmt.Println(string(r.([]byte)))

    // delete
    fmt.Println("delete class.master.company.manager")
    r, e = jc.Delete(jsoncrack.BYTES,false,in, "class", "master", "company", "manager")
    if e!=nil {
        panic(e)
    }
    fmt.Println(string(r.([]byte)))
}

5. Jsoncrack.Time

5.1 Available layouts

jsoncrack.Time can receive all kinds of time string format layouts below:

        "2006-01-02",
        "2006-1-2",

        "2006/01/02",
        "2006/1/2",

        "2006.01.02",
        "2006.1.2",

        "2006-01-02 15:04:05",
        "2006-1-2 15:04:05",

        "2006/01/02 15:04:05",
        "2006/1/2 15:04:05",

        "2006.01.02 15:04:05",
        "2006.1.2 15:04:05",
5.2 Example
func main() {
    type Time = jsoncrack.Time
    type VO struct {
        CreatedAt1  Time `json:"created_at1"`
        CreatedAt2  Time `json:"created_at2"`
        CreatedAt3  Time `json:"created_at3"`
        CreatedAt4  Time `json:"created_at4"`
        CreatedAt6  Time `json:"created_at6"`
        CreatedAt7  Time `json:"created_at7"`
        CreatedAt8  Time `json:"created_at8"`
        CreatedAt9  Time `json:"created_at9"`
        CreatedAt10 Time `json:"created_at10"`
        CreatedAt11 Time `json:"created_at11"`
        CreatedAt12 Time `json:"created_at12"`
        CreatedAt13 Time `json:"created_at13"`
    }
    var request = []byte(`{
        "created_at1": "2018-01-01",
        "created_at2": "2018-1-01",
        "created_at3": "2018/01/01",
        "created_at4": "2018/1/01",
        "created_at6": "2018.01.01",
        "created_at7": "2018.1.01",

        "created_at8": "2018-01-01 15:04:05",
        "created_at9": "2018-1-01 15:04:05",
        "created_at10": "2018.01.01 15:04:05",
        "created_at11": "2018.1.01 15:04:05",
        "created_at12": "2018/01/01 15:04:05",
        "created_at13": "2018/1/01 15:04:05"
    }`)
    vo := VO{}
    e = json.Unmarshal(request, &vo)
    if e != nil {
        fmt.Println(e.Error())
        return
    }
    jsoncrack.SmartPrint(vo, true)
}

Documentation

Index

Constants

View Source
const (
	MAP = 1 + iota
	ARRAY
	BYTES
)

Variables

This section is empty.

Functions

func CopyFrom

func CopyFrom(m map[string]interface{}) map[string]interface{}

copy a map to another

func GetString

func GetString(data []byte, keys ...string) string

func IfZero

func IfZero(arg interface{}) bool

func SmartPrint

func SmartPrint(i interface{}, escapeZero ...bool)

Types

type JsonCracker

type JsonCracker struct {
	Json JsonMarshaller
}

func NewCracker

func NewCracker(jsoner JsonMarshaller) JsonCracker

New a json-cracker instance jsoner == nil , official json marshaler will be put to use,otherwise use jsoner as specific

func (JsonCracker) Add

func (jc JsonCracker) Add(data []byte, k string, v interface{}, keys ...string) ([]byte, error)

add k-v pair into a json []byte

func (JsonCracker) Delete

func (jc JsonCracker) Delete(vtype int, safe bool, data []byte, keys ...string) (interface{}, error)

vtype: jsoncrack.MAP,jsoncrack.Array,jsoncrack.BYTES When vtype is 'jsoncrack.Map', it returns (map[string]interface{}, error), otherwise it returns (json.RawMessage,error) or ([]byte, error)

when safe is true, delete the specific key while not existed, throws an error. when safe is false, do nothing if not existed keys

Delete() returns the data modified already, while keeping the former data unchanged. When data is input , function will marshal its unmarshal object again to get a copy of data

func (JsonCracker) Get

func (jc JsonCracker) Get(vtype int, data []byte, keys ...string) (interface{}, error)

get a value via keys through a json []byte. value can specifc type as jsoncrack.BYTES or jsoncrack.MAP.The formmer returns json []bytes boxing in interface{},the other is a map[string]interface{} boxing in interface{}

func (JsonCracker) Marshal

func (jc JsonCracker) Marshal(dest interface{}) ([]byte, error)

json marshal via its jsoner realization

func (JsonCracker) MustUpdate

func (jc JsonCracker) MustUpdate(data []byte, k string, v interface{}, keys ...string) ([]byte, error)

When exists the key 'k' , it replace the origin value with v

func (JsonCracker) SafeUpdate

func (jc JsonCracker) SafeUpdate(data []byte, k string, v interface{}, keys ...string) ([]byte, error)

when exists the key 'k', it throws an error without replacing

func (*JsonCracker) SetJsoner

func (jc *JsonCracker) SetJsoner(jsoner JsonMarshaller)

set cracker's jsoner make sure the function executing while app is init, don't set while app is running. good:

func init(){
    jc.SetJsoner(yourJsoner)
}

bad:

func service() {
    jc.Marshal()
    ...
    jc.SetJsoner(yourJsoner)
    ...
}

func (JsonCracker) Unmarshal

func (jc JsonCracker) Unmarshal(data []byte, dest interface{}) error

json unmarshal via its jsoner realization

func (JsonCracker) Update

func (jc JsonCracker) Update(data []byte, k string, v interface{}, keys ...string) ([]byte, error)

update a json raw-message with a new key-value pair assume data:

{
   "class1": {
       "master": {
           "name": "Li Hua",
           "Age": 28
       },
      "students": [
          {
           "name": "Li Lei",
           "Age": 12
          },
          {
           "name": "Tom",
           "Age": 11
          }
      ]
   }
}

after exec jc.Update([]byte(data), "sub_name", "Li li", "class1", "master") returns:

{
   "class1": {
       "master": {
           "name": "Li Hua",
           "Age": 28,
           "sub_name":"Li li"
       },
      "students": [
          {
           "name": "Li Lei",
           "Age": 12
          },
          {
           "name": "Tom",
           "Age": 11
          }
      ]
   }
}

type JsonMarshaller

type JsonMarshaller interface {
	Marshal(interface{}) ([]byte, error)
	Unmarshal([]byte, interface{}) error
}

type Jsoner

type Jsoner struct {
}

a jsonMarshaller realization via the officials

func (Jsoner) Marshal

func (j Jsoner) Marshal(dest interface{}) ([]byte, error)

func (Jsoner) Unmarshal

func (j Jsoner) Unmarshal(data []byte, dest interface{}) error

type Time

type Time time.Time

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

func (Time) String

func (t Time) String() string

func (Time) Time

func (t Time) Time() time.Time

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(buf []byte) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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