Home  >  Article  >  Backend Development  >  Parse JSON string into map using json.Unmarshal function in golang

Parse JSON string into map using json.Unmarshal function in golang

WBOY
WBOYOriginal
2023-11-18 09:42:511606browse

Parse JSON string into map using json.Unmarshal function in golang

Use json.Unmarshal function in golang to parse JSON string into map

In golang, we can use json.Unmarshal function to parse JSON string into map. json.Unmarshal is a function that decodes JSON data into go values. Its basic syntax is as follows:

func Unmarshal(data []byte, v interface{}) error

where data is the JSON string to be parsed, and v is the go value used to store the parsing results.

Below, let us use a specific code example to demonstrate how to use the json.Unmarshal function to parse a JSON string into a map.

First, we need to import the required packages:

import (
    "encoding/json"
    "fmt"
)

Next, define a structure to store the parsing results. Since we parse the JSON string into a map, we can use the empty interface type as the type of the structure field to store various types of data.

type JsonMap struct {
    Data map[string]interface{} `json:"data"`
}

Then, we can write a function to parse the JSON string into a map and output the parsed result.

func parseJSON(jsonStr string) (map[string]interface{}, error) {
    var jsonData JsonMap
    err := json.Unmarshal([]byte(jsonStr), &jsonData)
    if err != nil {
        return nil, err
    }
    return jsonData.Data, nil
}

Finally, we can write a main function to test the above code.

func main() {
    jsonStr := `{
        "data": {
            "name": "John",
            "age": 30,
            "email": "john@example.com"
        }
    }`
    
    jsonData, err := parseJSON(jsonStr)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Println("Name:", jsonData["name"])
    fmt.Println("Age:", jsonData["age"])
    fmt.Println("Email:", jsonData["email"])
}

Run the above code, the output result is as follows:

Name: John
Age: 30
Email: john@example.com

The above is a specific code example of using the json.Unmarshal function in golang to parse a JSON string into a map. Hope this helps!

The above is the detailed content of Parse JSON string into map using json.Unmarshal function in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn