Home > Backend Development > Golang > How Do I Parse JSON Arrays of Maps into Go Structs?

How Do I Parse JSON Arrays of Maps into Go Structs?

Barbara Streisand
Release: 2024-12-14 00:10:09
Original
861 people have browsed it

How Do I Parse JSON Arrays of Maps into Go Structs?

Parsing JSON Arrays into Go Data Structures

When dealing with JSON data containing arrays, it can be challenging to choose the appropriate Go data structure to parse into. For instance, if a file holds an array of key-value pairs, attempts to utilize a map[string]string may result in an error like "cannot unmarshal array into Go value of type main.data."

The solution lies in accurately identifying the JSON structure. While the provided example appears to be an array, it is in fact an array of maps. The file should instead resemble the following to match the map[string]string structure:

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

Consider the following code snippet that demonstrates parsing an array of maps into a Go struct:

package main

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

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

When you run this code with a valid JSON file, it will successfully parse the data into the desired structure, providing you with access to the key-value pairs in the array.

The above is the detailed content of How Do I Parse JSON Arrays of Maps into Go Structs?. 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