Home >Backend Development >Golang >How to Unmarshal Nested JSON without Knowing its Structure?
Unmarshal Nested JSON without Knowing Structure
When working with a key-value store that contains JSON documents with varying schemas, it becomes challenging to unmarshal the JSON data into specific structs without knowing their structure beforehand. This article explores methods to address this issue and propose solutions.
Method 1: Unmarshal to Interface
To handle JSON documents with unknown structures, you can unmarshal them into an interface type, such as map[string]interface{}. This allows you to access the underlying data as a dictionary without needing to define a specific struct.
By unmarshalling the top-level foo namespace into a map[string]*json.RawMessage, you can retrieve the nested JSON data. However, you still need to determine the type of the data within the foo namespace to correctly unmarshal it into a struct.
Method 2: Regex Type Extraction
An alternative method is to extract the type string from the JSON data and use a regular expression to determine the struct type. Once the type is known, you can unmarshal the json.RawMessage into the appropriate struct.
Repeated Unmarshals
Whether repeated unmarshals are a concern depends on the performance requirements of your application. If speed is critical, it may be more efficient to unmarshal into a specific struct directly instead of using an intermediary interface. However, for small datasets or occasional use, the performance penalty may not be significant.
Update
Based on the update provided, two possible solutions are proposed:
a) Copy and Unmarshal
b) Regex and Unmarshal
The above is the detailed content of How to Unmarshal Nested JSON without Knowing its Structure?. For more information, please follow other related articles on the PHP Chinese website!