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

WBOY
Release: 2023-11-18 09:42:51
Original
1610 people have browsed it

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
Copy after login

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"
)
Copy after login

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"`
}
Copy after login

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
}
Copy after login

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"])
}
Copy after login

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

Name: John
Age: 30
Email: john@example.com
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template