Home >Backend Development >Golang >How to Unmarshal Nested JSON with Dynamic Keys Using Go?
Unmarshalling Nested JSON with Dynamic Keys
In complex JSON structures, encountering nested objects with dynamically changing keys can pose challenges during unmarshalling. Consider the following JSON data:
{ "message": { "Server1.example.com": [ { "application": "Apache", "host": { "name": "/^Server-[13456]/" }, "owner": "User1", "project": "Web", "subowner": "User2" } ], "Server2.example.com": [ { "application": "Mysql", "host": { "name": "/^Server[23456]/" }, "owner": "User2", "project": "DB", "subowner": "User3" } ] }, "response_ms": 659, "success": true }
Solution:
To effectively unmarshal such JSON, consider using a map[string]ServerStruct for the nested object with dynamic keys. This approach allows for the inclusion of multiple servers with unknown names.
Here's an example of an updated struct:
type YourStruct struct { Success bool ResponseMS int Servers map[string]*ServerStruct } type ServerStruct struct { Application string Owner string [...] }
By adding JSON tags, you can instruct the decoder to map specific JSON fields to the corresponding struct fields. Here are the updated tags:
type YourStruct struct { Success `json:"success"` ResponseMS `json:"response_ms"` Servers `json:"-"` } type ServerStruct struct { Application string `json:"application"` Owner string `json:"owner"` [...] }
The json:"-" tag on the "Servers" field ensures that the decoder skips mapping JSON fields directly to the "ServerStruct" field. Instead, it maps the fields to a map[string]ServerStruct.
This approach provides a flexible solution for unmarshalling nested JSON objects with dynamic keys, allowing you to access the data within each server object easily.
The above is the detailed content of How to Unmarshal Nested JSON with Dynamic Keys Using Go?. For more information, please follow other related articles on the PHP Chinese website!