Home > Article > Backend Development > How can I unmarshal nested JSON data without knowing its structure?
Unmarshalling Nested JSON Without Known Structure
When encountering nested JSON data without defined structures, there are several approaches to mitigate challenges in unmarshalling.
Avoiding Repeated Unmarshals
Minimizing unmarshalling operations is generally advisable. Consider implementing a caching mechanism to store unmarshalled objects for future use and avoid repetitive unmarshalling. However, in some cases, multiple unmarshalling may be necessary, especially when dealing with nested structures of varying types.
Determining the Correct Struct for Unmarshalling
Method 1: Unmarshal to map[string]interface{}
Unmarshal the json.RawMessage into a map[string]interface{}. This allows examination of the nested structure to identify the type and, subsequently, the correct struct to unmarshal into.
Example:
<code class="go">var objMap map[string]interface{} json.Unmarshal(rawMessage, &objMap)</code>
Method 2: Regular Expression Match
Use a regular expression to match the type string within the JSON data. Once the type is known, use reflection or a type switch to unmarshal into the corresponding struct.
Example:
<code class="go">type Regex *regexp.Regexp // Split the JSON data into key-value pairs type KeyValue struct { Key string Value string } // Regex for extracting the type var typeRE = Regex(regexp.MustCompile(`(?m)^.*"type": "(.+)".*$`)) // Unmarshal the raw message and extract the type func getType(rawMessage []byte) (string, error) { var data KeyValue err := json.Unmarshal(rawMessage, &data) if err != nil { return "", err } matches := typeRE.FindStringSubmatch(data.Value) return matches[1], nil }</code>
Using the Copy or Regular Expression Approach
Method A: Copy and Unmarshal
Method B: Regular Expression and Unmarshal
The above is the detailed content of How can I unmarshal nested JSON data without knowing its structure?. For more information, please follow other related articles on the PHP Chinese website!