Home > Article > Backend Development > How to parse different types of JSON-RPC tables
php editor Baicao introduces you how to parse different types of JSON-RPC tables. JSON-RPC is a lightweight remote procedure call protocol that is widely used in various web services. When parsing JSON-RPC tables, we need to pay attention to different types of table structures and data formats to ensure that the data is parsed and processed correctly. This article will introduce common JSON-RPC table types, including single tables, nested tables, and array tables, as well as corresponding parsing methods and precautions. By understanding the different types of JSON-RPC table parsing, we can better process and utilize data and improve the reliability and efficiency of our programs.
I want to get the information in a json-rpc file with the following structure:
{ "id": "foo1", "error": null, "result": [ { "key": [ "hello 1", 1, "world 1" ], "val": { "type": "static" } }, { "key": [ "hello 2", 1, "world 2" ], "val": { "type": "static" } } ] }
This is my parsing function, the key is a string table (int type cannot be accepted):
type jsonrpcrsp struct { id string `json:"id"` error *string `json:"error"` result json.rawmessage `json:"result"` } type jsonrpcentry_val struct { type string `json:"type"` } type jsonrpcentry struct { key [3]string `json:"key"` val jsonrpcentry_val `json:"val"` } jsonresult := jsonrpcrsp{} json.unmarshal(data, &jsonresult) entries := []jsonrpcentry{} for _, val := range jsonresult { json.unmarshal(val.result, &entries) }
How to parse the "key" table? ...the problem is that there are different types
The key table structure is:
[ <string>, <int>, <string>]
To unmarshal arrays of different types in go, if you need to access the type, you need to use interfaces and type assertions.
This may work for you:
type Result struct { Key [3]interface{} `json:"key"` Val struct { Type string `json:"type"` } `json:"val"` } msg := JsonRpcRsp{} json.Unmarshal(data, &msg) var result []Result json.Unmarshal(msg.Result, &result) for _, v := range result { key1 := v.Key[0].(string) key2 := v.Key[1].(float64) key3 := v.Key[2].(string) fmt.Println(key1, key2, key3) }
After asserting the three interfaces to their types, you can further use them according to your use case.
The above is the detailed content of How to parse different types of JSON-RPC tables. For more information, please follow other related articles on the PHP Chinese website!