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
Linda HamiltonOriginal
2024-12-07 07:07:191013browse

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"}
]

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
}

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

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)
}

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!

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