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
Mary-Kate OlsenOriginal
2024-12-16 20:36:12930browse

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

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

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

Example:

For the provided JSON file:

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

The output of the code would be:

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

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!

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