How to Unmarshall Nested JSON with Unknown Keys and Dynamic Server Names?

Barbara Streisand
Release: 2024-11-22 07:03:11
Original
330 people have browsed it

How to Unmarshall Nested JSON with Unknown Keys and Dynamic Server Names?

Unmarshalling Nested JSON with Unknown Keys

The challenge lies in parsing a JSON structure with an unknown number of outer keys and a confusingly structured nested key. Consider the following JSON format:

{
  "message": {
    "Server1.example.com": [],
    "Server2.example.com": []
  },
  "response_ms": 659,
  "success": true
}
Copy after login

Struct Definition Complications

The complexity stems from the absence of a clear key outside the server name and the dynamic nature of the outer keys. The initial attempt using a deeply nested struct:

type ServerDetails struct {
  Message struct {
    Hostname struct {
      Details struct {
        Application string `json:"application"`
      } `json:"-"`
    } `json:"-"`
  } `json:"message"`
}
Copy after login

fails due to the unknown server names and the single nested key without an outer key.

Dynamic Key Solution

To overcome these challenges, one can utilize a map[string]ServerStruct within the top-level struct. ServerStruct contains application, owner, and other relevant information specific to each server. JSON tags can be strategically added to ensure proper parsing.

Revised Struct Definition

type YourStruct struct {
    Success bool
    ResponseMS int
    Servers map[string]*ServerStruct
}

type ServerStruct struct {
    Application string
    Owner string
    [...]
}
Copy after login

JSON Tags and Unmarshalling

Additional JSON tags are necessary:

{
  "message": {
    "Server1.example.com": [
      {
        "application": "Apache",
        "host": {
          "name": "/^Server-[13456]/"
        },
        "owner": "User1",
        "project": "Web",
        "subowner": "User2"
      }
    ],
Copy after login

The "message" field now unmarshals into a map[string][]ServerStruct. Each key in the map represents a server name, and the corresponding value is an array of ServerStruct. The "host" field is ignored during unmarshalling using the "-" tag.

With these modifications, the JSON data can be successfully parsed into the revised struct.

The above is the detailed content of How to Unmarshall Nested JSON with Unknown Keys and Dynamic Server Names?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template