jsonDoc:=`[{ "name":"Ricardo Longa", "idade":28, "skills":["Golang","Android"]},{ "name":"Hery Victor", "idade":32, "skills":["Golang","Java"]}]`aJson:=djson.New().Parse(jsonDoc)
bJson, _:=aJson.Object(1) // now, bJson shares *djson.DO with aJsonbJson.Put(djson.Object{"hobbies": djson.Array{"game"}}) // append Array to ObjectbJson.UpdatePath(`["hobbies"][1]`, "running") // append value to ArraybJson.UpdatePath(`["hobbies"][0]`, "art") // replace value// must be like// [{"idade":28,"name":"Ricardo Longa","skills":["Golang","Android"]},// {"hobbies":["art","running"],"idade":32,"name":"Hery Victor","skills":["Golang","Java"]}]fmt.Println(aJson.ToString())
2.4. Default Value
jsonDoc:=`{ "name":"Ricardo Longa", "idade":28, "skills":["Golang","Android"]}`mJson:=djson.New().Parse(jsonDoc)
fmt.Println(mJson.Int("idade", 10)) // must be 28 which is int64fmt.Println(mJson.Int("name", 10)) // must be 10 because `name` field cannot be convert to integerfmt.Println(mJson.Int("hobbies", 10)) // must be 10 because no such field `hobbies`
2.5. To Structure
DJSON supports null package for sqlboiler (github.com/volatiletech/null)
typeUserstruct {
Idstring`json:"id"`Namestring`json:"name"`Email null.String`json:"email"`
}
varuserUsermJson:=djson.New().Put(
Object{
"id": "id-1234",
"name": "Ricardo Longa",
"email": "longa@test.com",
},
)
mJson.ToFields(&user, "id", "email") // only (`id`, `email`) tagfmt.Println(user) // must be {id-1234 {longa@test.com true}}
2.6. From Structure
typeUserstruct {
Idstring`json:"id"`Namestring`json:"name"`Email null.String`json:"email"`
}
varuser=User{
Id: "id-1234",
Name: "Ricardo Longa",
Email: null.String{
String: "longa@test.com",
Valid: true,
},
}
mJson:=djson.New()
mJson.FromFields(user) // no tag// must be like {"email":"longa@test.com","id":"id-1234","name":"Ricardo Longa"}fmt.Println(mJson.ToString())
2.7. From Map and Structure
typeNamestruct {
Firststring`json:"first"`Familystring`json:"family"`
}
user:=make(map[string]interface{})
user["id"] ="id-1234"user["name"] =Name{
First: "Ricardo",
Family: "Longa",
}
user["email"] = null.String{
String: "longa@test.com",
Valid: true,
}
mJson:=djson.New()
mJson.FromFields(user, "name.first", "email") // tag has depth concept// must be like {"email":"longa@test.com","name":{"first":"Ricardo"}}fmt.Println(mJson.ToString())