Home >Backend Development >Golang >How Can I Add a 'count' Key to a JSON String with an Unknown Structure?
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!