2016-11-13 24 views
3

我有一个JSON对象,这样的事情:解组JSON与未知的字段名称

{ 
    "randomstring": { 
     "everything": "here", 
     "is": "known" 
    } 
} 

基本上是所有里面的randomstring对象是已知的,我可以模拟,但randomstring本身是随机的。我知道它会怎样,但每次都会有所不同。基本上我需要的所有数据都是在randomstring对象中。我怎么能解析这种JSON来获取数据?

+3

解组成'图[字符串] SomeParticularStructType'。 – twotwotwo

+3

http://stackoverflow.com/questions/35558039/how-to-unmarshal-json-with-dynamic-key-which-cant-be-captured-as-a-json-in-st和http: //stackoverflow.com/questions/15817720/golang-struct-for-json-with-arbitrary-keys –

回答

6

其中关键的类型是string和值类型是你想要的领域,一个结构像this example on the Playground及以下使用地图:

package main 

import (
    "encoding/json" 
    "fmt" 
    "log" 
) 

type Item struct{ X int } 

var x = []byte(`{ 
    "zbqnx": {"x": 3} 
}`) 

func main() { 
    m := map[string]Item{} 
    err := json.Unmarshal(x, &m) 
    if err != nil { 
     log.Fatal(err) 
    } 
    fmt.Println(m) 
}