Home > Backend Development > Golang > How to Unmarshal Nested JSON with Dynamic Keys Using Go?

How to Unmarshal Nested JSON with Dynamic Keys Using Go?

DDD
Release: 2024-11-22 06:52:15
Original
257 people have browsed it

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

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
    [...]
}
Copy after login

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"`
    [...]
}
Copy after login

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!

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