Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
Another tutorial to be recorded here after helping a newbie to Golang. His problem was how to deal with JSON data that have inner block. Such as :
family := `{
"name": "BiBi",
"parents": {
"mother": "MaMa",
"father": "PaPa"
}
}`
and how to unmarshal the JSON inner/nested value of parents and assign the data to specific structure?
To deal with JSON inner block, the solution is stiil to unmarshal the JSON data with the standard way of un-marshaling JSON data and access the inner/nested values of parents by doing additional mapping to the MyMother and MyFather structs. See code example below.
package main
import (
"encoding/json"
"fmt"
)
type MyMother struct {
Name string
Mother string
}
type MyFather struct {
Name string
Father string
}
type Family struct {
Name string
Parents struct {
Mother string
Father string
}
}
var jsonData = `{
"name": "BiBi",
"parents": {
"mother": "MaMa",
"father": "PaPa"
}
}`
func main() {
jsonFamily := &Family{}
err := json.Unmarshal([]byte(jsonData), jsonFamily)
if err != nil {
fmt.Println(err)
}
// assign to MyMother
mama := &MyMother{Name: jsonFamily.Name, Mother: jsonFamily.Parents.Mother}
fmt.Println(mama.Name + " 's mother is " + mama.Mother)
// assign to MyFather
papa := &MyFather{Name: jsonFamily.Name, Father: jsonFamily.Parents.Father}
fmt.Println(papa.Name + " 's father is " + papa.Father)
}
Output :
BiBi 's mother is MaMa
BiBi 's father is PaPa
Hope that this tutorial can be useful to you.
See also : Golang : How to create new XML file ?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.4k Golang : Set, Get and List environment variables
+6.4k Golang : Convert an executable file into []byte example
+4.2k Javascript : How to show different content with noscript?
+28.5k Golang : Detect (OS) Operating System
+16.2k Golang : Execute terminal command to remote machine example
+23.7k Golang : Use regular expression to validate domain name
+5.7k Golang : Detect variable or constant type
+6.2k Golang : Test input string for unicode example
+17.6k Golang : How to make a file read only and set it to writable again?
+10.9k Golang : Web routing/multiplex example
+8.3k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+7.7k Golang : Gomobile init produce "iphoneos" cannot be located error