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)) }
Output:
{"votes":{"option_A":"3"},"count":1}
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!