Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.
Syntax: func Unmarshal(data []byte, v interface{}) error
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. Example 1:
Go
package main
import (
"encoding/json"
"fmt"
)
type Country struct {
Name string
Capital string
Continent string
}
func main() {
var country1 Country
Data := [] byte (`{
"Name": "India",
"Capital": "New Delhi",
"Continent": "Asia"
}`)
err := json.Unmarshal(Data, &country1)
if err != nil {
fmt.Println(err)
}
fmt.Println("Struct is:", country1)
fmt.Printf("%s's capital is %s and it is in %s.\n", country1.Name,
country1.Capital, country1.Continent)
}
|
Output:
Struct is: {India New Delhi Asia}
India's capital is New Delhi and it is in Asia.
Example 2:
Go
package main
import (
"encoding/json"
"fmt"
)
type Country struct {
Name string
Capital string
Continent string
}
func main() {
var country []Country
Data := [] byte (`
[
{"Name": "Japan", "Capital": "Tokyo", "Continent": "Asia"},
{"Name": "Germany", "Capital": "Berlin", "Continent": "Europe"},
{"Name": "Greece", "Capital": "Athens", "Continent": "Europe"},
{"Name": "Israel", "Capital": "Jerusalem", "Continent": "Asia"}
]`)
err := json.Unmarshal(Data, &country)
if err != nil {
fmt.Println(err)
}
for i := range country {
fmt.Println(country[i].Name + " - " + country[i].Capital +
" - " + country[i].Continent)
}
}
|
Output:
Japan - Tokyo - Asia
Germany - Berlin - Europe
Greece - Athens - Europe
Israel - Jerusalem - Asia
Parse JSON to map
In some cases, we do not know the structure of the JSON beforehand, so we cannot define structs to unmarshal the data. To deal with cases like this we can create a map[string]interface{}
Example 1:
Go
package main
import (
"encoding/json"
"fmt"
)
func main() {
var person map [ string ] interface {}
jsonData := `{
"name" : "Jake" ,
"country" : "US" ,
"state" : "Connecticut"
}`
err := json.Unmarshal([] byte (jsonData), &person)
if err != nil {
fmt.Println( "Error while decoding the data" , err.Error())
}
fmt.Println( "The name of the person is" , person[ "name" ], "and he lives in" , person[ "country" ])
}
|
Output:
The name of the person is Jake and he lives in US
Example 2:
Go
package main
import (
"encoding/json"
"fmt"
)
func main() {
var persons [] map [ string ] interface {}
jsonData := `[{
"name" : "Jake" ,
"country" : "US" ,
"state" : "Connecticut"
},
{
"name" : "Jacob" ,
"country" : "US" ,
"state" : "NewYork"
},
{
"name" : "James" ,
"country" : "US" ,
"state" : "WashingtonDC"
}
]`
err := json.Unmarshal([] byte (jsonData), &persons)
if err != nil {
fmt.Println( "Error while decoding the data" , err.Error())
}
for index, person := range persons {
fmt.Println( "Person:" , index+ 1 , "Name:" , person[ "name" ], "Country:" , person[ "country" ], "State:" , person[ "state" ])
}
}
|
Output:
Person: 1 Name: Jake Country: US State: Connecticut
Person: 2 Name: Jacob Country: US State: NewYork
Person: 3 Name: James Country: US State: WashingtonDC
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Mar, 2023
Like Article
Save Article