Home >Backend Development >Golang >How Can I Decode JSON with a Variable Structure in Go?

How Can I Decode JSON with a Variable Structure in Go?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-01 01:58:11663browse

How Can I Decode JSON with a Variable Structure in Go?

Decoding JSON with Variable Structure

When working with JSON data, it can be challenging to deal with data structures that vary. In such cases, conventional methods like json.Unmarshal() using fixed structs become impractical. Here's a solution for this scenario:

Solution:Unmarshal into map[string]interface{}

Instead of relying on predefined structs, we can unmarshal the JSON into a generic map[string]interface{} type. This allows us to handle JSON data with varying structures.

Consider the following JSON:

{ "votes": { "option_A": "3" } }

To add a "count" key to this JSON, we can unmarshal it as follows:

package main

import (
    "encoding/json"
)

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

This approach allows us to easily modify the JSON structure without being bound to a fixed data model. The map[string]interface{} type provides flexibility in handling dynamic JSON structures.

The above is the detailed content of How Can I Decode JSON with a Variable Structure 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
Previous article:Go Generics: A Deep DiveNext article:Go Generics: A Deep Dive