Open In App

How to Parse JSON in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Golang program to illustrate the
// concept of parsing json to struct
package main
 
import (
    "encoding/json"
    "fmt"
)
 
// declaring a struct
type Country struct {
 
    // defining struct variables
    Name      string
    Capital   string
    Continent string
}
 
// main function
func main() {
 
    // defining a struct instance
    var country1 Country
 
    // data in JSON format which
    // is to be decoded
    Data := []byte(`{
        "Name": "India", 
        "Capital": "New Delhi",
        "Continent": "Asia"
    }`)
 
    // decoding country1 struct
    // from json format
    err := json.Unmarshal(Data, &country1)
 
    if err != nil {
 
        // if error is not nil
        // print error
        fmt.Println(err)
    }
 
    // printing details of
    // decoded data
    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




// Golang program to illustrate the
// concept of parsing JSON to an array
package main
 
import (
    "encoding/json"
    "fmt"
)
 
// declaring a struct
type Country struct {
 
    // defining struct variables
    Name      string
    Capital   string
    Continent string
}
 
// main function
func main() {
 
    // defining a struct instance
    var country []Country
 
    // JSON array to be decoded
    // to an array in golang
    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"}
    ]`)
 
    // decoding JSON array to
    // the country array
    err := json.Unmarshal(Data, &country)
 
    if err != nil {
 
        // if error is not nil
        // print error
        fmt.Println(err)
    }
 
    // printing decoded array
    // values one by one
    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




//program to illustrate the concept of parsing JSON to map
package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
 
    //declaring a map
    //key of type string and value as type interface{} to store values of any type
    var person map[string]interface{}
     
    //json data to be decoded
    jsonData := `{
        "name":"Jake",
        "country":"US",
        "state":"Connecticut"
    }`
     
    //decoding the json data and storing in the person map
    err := json.Unmarshal([]byte(jsonData), &person)
     
    //Checks whether the error is nil or not
    if err != nil {
     
        //Prints the error if not nil
        fmt.Println("Error while decoding the data", err.Error())
    }
 
    //printing the details of decoded data
    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




// Golang program to illustrate the
// concept of parsing JSON to an array
package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
 
    //defining the array of persons
    var persons []map[string]interface{}
 
    //json array to be decoded to an array in golang
    jsonData := `[{
        "name":"Jake",
        "country":"US",
        "state":"Connecticut"
    },
    {
        "name":"Jacob",
        "country":"US",
        "state":"NewYork"
    },
    {
        "name":"James",
        "country":"US",
        "state":"WashingtonDC"
    }
    ]`
 
    //decoding JSON array to persons array
    err := json.Unmarshal([]byte(jsonData), &persons)
 
    if err != nil {
        fmt.Println("Error while decoding the data", err.Error())
    }
 
    //printing decoded array values one by one
    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


Last Updated : 23 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads