What does the Golan equivalent of converting any JSON to a standard dict in Python mean?

In Python, you can do something like this:

r = requests.get("http://wikidata.org/w/api.php", params=params)
data = r.json()

And now it datais a table of dict or hashes (I also did not need to predefine the dict structure), and I can access the values ​​of the keys by executing data ["entity"], data [entities "] [" Q12 "], etc. .

How will I do this in golang? So far I have this:

resp, err := http.Get("http://wikidata.org/w/api.php?"+v.Encode())
if err != nil {
    // handle error
}

defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var data interface{}
decodeErr := decoder.Decode(&data)
if decodeErr != nil {
    // handle error
}
fmt.Println(data["entities"], data["entities"]["Q"+id])

Which gives me a compilation error: invalid operation: data["entities"] (index of type interface {})

What type should var databe? And do I need to predefine the structure for JSON or can I process any JSON file / stream without changing the code?

+4
source share
1 answer

, Go map[string]interface{} ( map string ):

var data map[string]interface{}

, :

data["entities"]

. :

s := `{"text":"I'm a text.","number":1234,"floats":[1.1,2.2,3.3],
    "innermap":{"foo":1,"bar":2}}`

var data map[string]interface{}
err := json.Unmarshal([]byte(s), &data)
if err != nil {
    panic(err)
}

fmt.Println("text =", data["text"])
fmt.Println("number =", data["number"])
fmt.Println("floats =", data["floats"])
fmt.Println("innermap =", data["innermap"])

innermap, ok := data["innermap"].(map[string]interface{})
if !ok {
    panic("inner map is not a map!")
}
fmt.Println("innermap.foo =", innermap["foo"])
fmt.Println("innermap.bar =", innermap["bar"])

fmt.Println("The whole map:", data)

:

text = I'm a text.
number = 1234
floats = [1.1 2.2 3.3]
innermap = map[foo:1 bar:2]
innermap.foo = 1
innermap.bar = 2
The whole map: map[text:I'm a text. number:1234 floats:[1.1 2.2 3.3]
    innermap:map[foo:1 bar:2]]

Go Playground.

:

, (map map), "innermap" , , , :

innermap, ok := data["innermap"].(map[string]interface{})
// If ok, innermap is of type map[string]interface{}
// and you can refer to its elements.
+18

All Articles