Home >Backend Development >Golang >How to Represent a JSON Array with Dynamic Keys in a Go Struct?

How to Represent a JSON Array with Dynamic Keys in a Go Struct?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 19:49:11240browse

How to Represent a JSON Array with Dynamic Keys in a Go Struct?

Go Struct Representation for JSON Array with Dynamic Keys

Consider a JSON file containing an array:

[
  {"a" : "1"},
  {"b" : "2"},
  {"c" : "3"}
]

Despite attempting to parse it as a map of strings to strings, an error arises:

json: cannot unmarshal array into Go value of type main.data

To resolve this, we need a Go structure that mirrors the JSON array format.

The correct approach can be found here: https://play.golang.org/p/8nkpAbRzAD

type mytype []map[string]string

func main() {
    var data mytype
    file, err := ioutil.ReadFile("test.json")
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(file, &data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(data)
}

This definition declares mytype as a slice of maps, aligning with the structure of the JSON array. It allows for the correct parsing and representation of the JSON data in a Go struct.

The above is the detailed content of How to Represent a JSON Array with Dynamic Keys in a Go Struct?. 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