Home > Backend Development > Golang > How to Parse a JSON Array of Dynamic Key-Value Pairs in Go?

How to Parse a JSON Array of Dynamic Key-Value Pairs in Go?

Mary-Kate Olsen
Release: 2024-12-16 20:36:12
Original
839 people have browsed it

How to Parse a JSON Array of Dynamic Key-Value Pairs in Go?

Parsing a JSON Array into a Data Structure in Go

When working with JSON data in Go, it's essential to understand the appropriate data structures for different JSON formats. In this case, we are dealing with a JSON array of dynamic key-value pairs.

Problem:

You are attempting to parse a JSON file containing an array of JSON objects. However, using a simple map[string]string to represent the data results in an error:

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

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

Solution:

To correctly parse the JSON array, you need to define a data structure that represents the array of objects. This can be achieved using a custom type that embeds a slice of maps.

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

Code:

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

Example:

For the provided JSON file:

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

The output of the code would be:

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

The above is the detailed content of How to Parse a JSON Array of Dynamic Key-Value Pairs in Go?. 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