Home > Backend Development > Golang > How to Parse JSON Arrays with Dynamic Keys into Go Data Structures?

How to Parse JSON Arrays with Dynamic Keys into Go Data Structures?

Linda Hamilton
Release: 2024-12-07 07:07:19
Original
921 people have browsed it

How to Parse JSON Arrays with Dynamic Keys into Go Data Structures?

Parsing JSON Arrays into Go Data Structures

In Golang, parsing JSON data into custom data structures can be straightforward. Consider a scenario where a JSON file contains an array of objects with dynamic keys:

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

Attempting to parse this JSON into a map[string]string may result in an error:

import (
    "encoding/json"
    "io/ioutil"
    "log"
)

type data map[string]string

func main() {
    c, _ := ioutil.ReadFile("test.json")
    dec := json.NewDecoder(bytes.NewReader(c))
    var d data
    dec.Decode(&d) // error: cannot unmarshal array into Go value of type data
}
Copy after login

To resolve this issue and parse the JSON array, a custom type mytype is defined as an array of maps:

type mytype []map[string]string
Copy after login

By defining the data structure as a slice of maps, the JSON array can be parsed accordingly:

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
)

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 approach allows for parsing of JSON arrays with dynamic keys into a Go data structure.

The above is the detailed content of How to Parse JSON Arrays with Dynamic Keys into Go Data Structures?. 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