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
Release: 2024-12-08 19:49:11
Original
244 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template