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!