Home > Backend Development > Golang > How to Unmarshal JSON with Unknown Field Names into a Go Struct?

How to Unmarshal JSON with Unknown Field Names into a Go Struct?

Susan Sarandon
Release: 2024-12-17 11:45:25
Original
333 people have browsed it

How to Unmarshal JSON with Unknown Field Names into a Go Struct?

Unmarshaling JSON with Unknown Fieldnames to a Struct

This scenario arises when the JSON response contains fields with unknown or dynamic names. To address this, we can utilize a combination of a map and a struct to capture the data.

Modified Code:

package main

import "fmt"
import "encoding/json"

var body = []byte(`{
    "unknown_field": {
            "known_field_1": [[1,2,3,4,5],[10,20,30,40,50],[100,200,300,400,500]],
            "known_field_2": [[11,21,31,41,51]],
            "known_field_3": [[12,22,32,42,52],[14,44,34,44,54]]
        }
}`)

type mData struct {
    KnownField1 [][5]int `json:"known_field_1"`
    KnownField2 [][5]int `json:"known_field_2"`
    KnownField3 [][5]int `json:"known_field_3"`
}

var data map[string]mData

func main() {
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }

    fmt.Println(data)
    for k, v := range data {
        fmt.Println(k, v)
    }
}
Copy after login

Explanation:

  • We define a mData struct to represent the known fields in the JSON.
  • We create a map data, where the keys are the unknown fieldnames and the values are instances of mData.
  • During unmarshalling, json.Unmarshal assigns the JSON data to the corresponding fields in mData based on the field names.
  • The keys of the data map are the dynamic fieldnames from the JSON.

Output:

map[unknown_field:{[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}]
unknown_field {[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}
Copy after login

The above is the detailed content of How to Unmarshal JSON with Unknown Field Names into a Go Struct?. 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