Home > Article > Backend Development > How to Unmarshall Arbitrary JSON Data in Sections Based on a Code?
In certain scenarios, it may be necessary to unmarshall JSON data in parts or sections. For instance, the upper half of the data might indicate the action to perform on the lower half, such as unmarshalling into a specific struct based on the "code" in the upper half.
Consider the following sample structures:
<code class="go">type Range struct { Start int End int } type User struct { ID int Pass int }</code>
As an example, the JSON data could resemble the following:
<code class="json">// Message with "Code" 4, signifying a Range structure { "Code": 4, "Payload": { "Start": 1, "End": 10 } } // Message with "Code" 3, signifying a User structure { "Code": 3, "Payload": { "ID": 1, "Pass": 1234 } }</code>
To achieve this unmarshalling, we can delay parsing the bottom half of the JSON data until we have determined the code in the top half. Consider the following approach:
<code class="go">import ( "encoding/json" "fmt" ) type Message struct { Code int Payload json.RawMessage // Delay parsing until we know the code } func MyUnmarshall(m []byte) { var message Message var payload interface{} json.Unmarshal(m, &message) // Delay parsing until we know the color space switch message.Code { case 3: payload = new(User) case 4: payload = new(Range) } json.Unmarshal(message.Payload, payload) // Error checks omitted for readability fmt.Printf("\n%v%+v", message.Code, payload) // Perform actions on the data } func main() { json := []byte(`{"Code": 4, "Payload": {"Start": 1, "End": 10}}`) MyUnmarshall(json) json = []byte(`{"Code": 3, "Payload": {"ID": 1, "Pass": 1234}}`) MyUnmarshall(json) }</code>
By using this approach, you can effectively unmarshall arbitrary JSON data in sections, depending on the specified code.
The above is the detailed content of How to Unmarshall Arbitrary JSON Data in Sections Based on a Code?. For more information, please follow other related articles on the PHP Chinese website!