Home > Backend Development > Golang > How to Efficiently Parse a JSON Array into a Go Data Structure?

How to Efficiently Parse a JSON Array into a Go Data Structure?

DDD
Release: 2024-12-22 01:40:30
Original
338 people have browsed it

How to Efficiently Parse a JSON Array into a Go Data Structure?

Parsing JSON Array into Data Structure in Go

When dealing with JSON data structured as an array, utilizing a Go map might encounter limitations. A more suitable approach is to define a custom data structure to accommodate the specific format of the data.

An example JSON array:

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

To parse this array, a custom type can be defined:

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

This type represents an array of maps, where each map element corresponds to an object in the JSON array.

Here's how to parse the JSON array into the custom type:

package main

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

By reading the file and unmarshaling its contents into the data variable of type mytype, the JSON array is successfully parsed into a Go structure. The data variable can then be used to access the individual objects in the array.

The above is the detailed content of How to Efficiently Parse a JSON Array into a Go Data Structure?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template