This is a creation in Article, where the information may have evolved or changed.
Today encountered an interface need to work with a JSON map type array, the idea is to use the array in the Simple-json to read arrays, and then iterate through the array to fetch each map, and then read the corresponding values, in the subsequent operation, seemingly very simple work, but encountered a trap.
The JSON format is similar to the bottom:
{"Code": 0, "request_id": xxxx, "code_msg": "", "body": [{ "device_id": "xxxx" , "Device_hid": "XXXX"}], "Count" : 0}
Soon according to the above ideas to write the code, but it happened, compile, but look at the code logic there is no problem, where is the problem?
The original is interface{} The array method returned is a interface{} type, we are all in Golang interface is a universal recipient can save any type of argument, but ignore the point, it is not to take for granted when any type to use, Be sure to judge the interface type before using it. I ignored this at first, and took the interface variable for granted to cause the error.
Here's a small example.
Package Mainimport ("Encoding/json" "FMT" "Github.com/bitly/go-simplejson") func main () {//Patchwork JSON body as map array var rbod y []map[string]interface{}t: = Make (map[string]interface{}) t["device_id"] = "dddddd" t["device_hid"] = "ddddddd" Rbody = Append (rbody, t) T1: = Make (map[string]interface{}) t1["device_id"] = "AAAAA" t1["device_hid"] = "AAAAA" rbody = Append ( Rbody, t1) Cnnjson: = Make (map[string]interface{}) cnnjson["code"] = 0cnnjson["request_id"] = 123cnnjson["code_msg"] = "" cnnjson["Body"] = rbodycnnjson["page"] = 0cnnjson["page_size"] = 0b, _: = json. Marshal (Cnnjson) cnnn: = string (b) fmt. Println ("cnnn:%s", cnnn) Cn_json, _: = Simplejson. Newjson ([]byte (cnnn)) Cn_body, _: = Cn_json. Get ("Body"). Array () For _, di: = Range Cn_body {//Here is the type judgment for Di newdi, _: = Di. map[string]interface{}) device_id: = newdi["device_id"]device_hid: = newdi["Device_hid"]fmt. Println (Device_hid, device_id)}}