Home >Backend Development >Golang >How Can I Add a 'count' Key to a JSON String with an Unknown Structure?

How Can I Add a 'count' Key to a JSON String with an Unknown Structure?

DDD
DDDOriginal
2024-12-08 15:35:13543browse

How Can I Add a

Decoding JSON with an Unknown Structure

The question arises when attempting to modify a JSON string of an unknown structure. The objective is to add a "count" key to the existing JSON:

Original JSON:

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

Desired JSON:

{ "votes": { "option_A": "3" }, "count": "1" }

The challenge lies in the variability of the JSON structure, making it impractical to use a conventional JSON decoder with a predetermine structure.

Solution: Unmarshal into a Map

To overcome this challenge, a practical approach is to unmarshal the JSON into a map of strings to interfaces:

var raw map[string]interface{}
json.Unmarshal(in, &raw)

This allows for the manipulation of the JSON data on a key-value basis. In this case, a new "count" key can be added:

raw["count"] = 1

To generate the desired JSON string, the modified map is remarshaled into a JSON string:

out, err := json.Marshal(raw)

As a result, the unknown JSON structure can be modified and the "count" key can be added as desired.

The above is the detailed content of How Can I Add a 'count' Key to a JSON String with an Unknown Structure?. 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