TommyLemon / go.jsonvalue

A tool for JSON operation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Jsonvalue - A Go package for fast and convient JSON marshal and unmarshaling

Travis Coveralls Go report Codebeat
GoDoc Latest License

中文版

Jsonvalue is a Golang package for JSON parsing. It is used in situations those Go structures cannot achieve, or map[string]interface{} could not do properbally.

Quick Start

Sometimes we want to create a complex JSON object like:

{
    "someObject": {
        "someObject": {
            "someObject": {
                "message": "Hello, JSON!"
            }
        }
    }
}

With jsonvalue, It is quite simple to achieve this:

    v := jsonvalue.NewObject()
    v.SetString("Hello, JSON").At("someObject", "someObject", "someObject", "message")
    fmt.Println(v.MustMarshalString())
    // Output:
    // {"someObject":{"someObject":{"someObject":{"message":"Hello, JSON!"}}}

Playground

Similarly, it is quite easy to create sub-arrays like:

[
    {
        "someArray": [
            "Hello, JSON!"
        ]
    }
]
    v := jsonvalue.NewArray()
    v.SetString("Hello, JSON").At(0, "someObject", 0)
    fmt.Println(v.MustMarshalString())
    // Output:
    // [{"someObject":["Hello, JSON"]}]

Playground

In opposite, to parse and read the first JSON above, you can use jsonvalue like this:

	const raw = `{"someObject": {"someObject": {"someObject": {"message": "Hello, JSON!"}}}}`
	s := jsonvalue.MustUnmarshalString(s).GetString("someObject", "someObject", "someObject", "message")
	fmt.Println(v.MustMarshalString())
	// Output:
	// Hello, JSON!

However, it is quite complex and annoying in automatically creating array. I strongly suggest using SetArray() to create the array first, then use Append() or Insert() to set array elements. Please refer go godoc.

About

A tool for JSON operation

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:Go 100.0%