github地址 https://github.com/hljdxjiang/gojson
代码使用示例
package main
import (
"fmt"
"github.com/hljdxjiang/gojson"
)
func main() {
JsonObjectTest()
JsonArrayTest()
}
func JsonObjectTest() {
jsonString := `{"a1":"a1"}`
jo, err := gojson.JsonObject(jsonString)
if err != nil {
fmt.Println(err)
}
jo.SetKey("a2", "a2")
fmt.Println(jo.Encode()) //{"a1":"a1","a2":"a2"}
//update a1.value
jo.SetKey("a1", "a3")
fmt.Println(jo.Encode()) //{"a1":"a3","a2":"a2"}
//new a json without item
njo := gojson.NewJsonObject()
njo.SetKey("ad1", "ad1") //{"ad1":"ad1"}
fmt.Println(njo.Encode())
//add another JsonObject
njo.AppendObject(*jo)
fmt.Println(njo.Encode()) //{"ad1":"ad1","a1":"a3","a2":"a2"}
njo.SetKey("addJson", *jo)
fmt.Println(njo.Encode()) //{"ad1":"ad1","a1":"a3","a2":"a2","addJson":{"a1":"a3","a2":"a2"}}
fmt.Println(njo.GetValueByIndex(1).AsString("")) //a2
for _, val := range njo.GetKeys() {
fmt.Println(njo.GetValue(val).AsString(""))
}
fmt.Println(jo.GetIndex("a2"))
fmt.Println(jo.GetValueByIndex(1).AsString())
}
func JsonArrayTest() {
jsonarrString := `["aa","bb"]`
ja, err := gojson.JsonArray(jsonarrString)
if err != nil {
fmt.Println(err)
}
ja.AddItem("cc")
jsonString := `{"a1":"a1"}`
jo, err := gojson.JsonObject(jsonString)
if err != nil {
fmt.Println(err)
}
ja.AddItem(*jo)
fmt.Println(ja.Encode()) //["aa","bb","cc",{"a1":"a1"}]
nja := gojson.NewJsonArray()
nja.AddItem("ff")
nja.Append(*ja)
fmt.Println(nja.Encode()) //{"ad1":"ad1","a1":"a3","a2":"a2","addJson":{"a1":"a3","a2":"a2"}}
}
有疑问加站长微信联系(非本文作者)