Home > Backend Development > Golang > How Can I Add a 'count' Property to Dynamic JSON Data in Go?

How Can I Add a 'count' Property to Dynamic JSON Data in Go?

Susan Sarandon
Release: 2024-12-08 15:27:15
Original
487 people have browsed it

How Can I Add a

JSON Decoding with Dynamic Structure

When dealing with JSON data of unknown or varying structure, it becomes challenging to decode it using predefined structs in Go. To overcome this issue, we can employ a more flexible approach.

Solution: Unmarshal into a Map

Firstly, we Unmarshal the JSON into a map[string]interface{}, which is a type-flexible data structure in Go. This allows us to access the JSON properties as strings and their corresponding values as generic interfaces.

Adding the "count" Property

Once the JSON is unmarshaled into a map, we can manipulate it freely. In this case, we can assign a new key-value pair with the key "count" and the value being the desired count.

Marshaling Back to JSON

Finally, we Marshal the modified map back into a JSON string. This process involves serializing the map into JSON format, which will produce the desired output with the added "count" property.

Example Code

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)

    // Unmarshal into a map
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }

    // Add the "count" property
    raw["count"] = 1

    // Marshal back to JSON
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(out))
}
Copy after login

Output:

{"votes":{"option_A":"3"},"count":1}
Copy after login

The above is the detailed content of How Can I Add a 'count' Property to Dynamic JSON Data 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