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
Release: 2024-12-08 15:35:13
Original
578 people have browsed it

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" } }
Copy after login

Desired JSON:

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

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)
Copy after login

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
Copy after login

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

out, err := json.Marshal(raw)
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template