SoFunction
Updated on 2025-03-05

Implementation of go language string to structure

In Go, you can use the encoding/json package in the standard library to convert strings in JSON format to structures.

Suppose there is the following JSON string:

{
    "name": "Brother Chicken",
    "age": 28,
    "gender": "male",
    "hobby": {
        "sing": "Sing",
        "jump": "Jump",
        "rap": "rap",
        "ball":"basketball"
    }
}

You can define a corresponding structure type:

type hobby struct {
    Sing    string  `json:"sing"`
    Jump    string `json:"jump"`
    Rap     string  `json:"rap"`
    Hobby hobby    `json:"hobby"`
}

type Person struct {
    Name string `json:"name"`
    Age string  `json:"age"`
    Gender string `json:"gender`
    Hobby hobby `json:"hobby"`
}

Then use the () function to parse the JSON string into an instance of the structure type:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonStr := `{
    "name": "Brother Chicken",
    "age": 28,
    "gender": "male",
    "hobby": {
        "sing": "Sing",
        "jump": "Jump",
        "rap": "rap",
        "ball":"basketball"
    }
}`

    var person Person
    if err := ([]byte(jsonStr), &person); err != nil {
        ("Parse JSON failed:", err)
        return
    }

    ("Host: %s\nSing: %d\nSkip: %s\nHost: %v\n", , , , )
}

In this example, we parse the JSON string jsonStr into a structure instance person of type Person. &person means passing the address of person to the () function, allowing it to populate the parsed result into person. If parsing fails, a non-empty error object will be returned.

This is the end of this article about the implementation of go language string to structure. For more related go language string to structure content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!