Home > Backend Development > Golang > How to Unmarshal JSON with Unknown Field Names in Go Using a Map?

How to Unmarshal JSON with Unknown Field Names in Go Using a Map?

DDD
Release: 2024-12-26 03:32:09
Original
315 people have browsed it

How to Unmarshal JSON with Unknown Field Names in Go Using a Map?

Unmarshaling JSON with Unknown Fieldnames Using a Map

Unmarshaling JSON with unknown fieldnames poses a challenge, especially when the object structure remains consistent. This question addresses how to handle such scenarios and provides a solution using a Golang map.

Problem:

The provided JSON response from a POST request contains a field with an unknown name. The goal is to unmarshal this JSON into a struct while preserving the consistent structure of the known fields.

Solution:

Step 1: Create a Struct for the Known Fields

Define a struct named mData that represents the consistent fields in the JSON:

Step 2: Use a Map to Handle Unknown Fieldnames

Create a map called data to store the unknown fieldname as a key and an instance of mData as the value:

Step 3: Unmarshal the JSON into the Map

Utilize json.Unmarshal to bind the JSON body to the map:

Step 4: Print the Results

The map will now contain the unknown fieldname and the associated mData instance. You can access the values using the following code:

This approach allows you to unmarshal JSON with unknown fieldnames while maintaining the structure of the known fields. The output of the provided code will be:

The above is the detailed content of How to Unmarshal JSON with Unknown Field Names in Go Using a Map?. 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