如何使用golang打印json文档中“org”下当前字段中存储的所有元素?

时间:2018-01-23 16:31:43

标签: json dictionary go glide-golang

更新的json如下:

    {
     "phone":[
                {"home":"58878767"},
                {"mobile":"32453543"}
              ],
     "org": [
    {
        "current": {
            "org_dept": "Hr",
            "org_eptime": "1516354574432",
            "org_name": "Uejsjak",
            "org_title": "Hakosklaks"
        }
    },
    {
        "current": {
            "org_dept": "Accounts",
            "org_eptime": "1516354561184",
            "org_name": "Abcd",
            "org_title": "Hakahkshsjs"
        },
    {
        "past": {
            "org_dept": "Backend",
            "org_eptime": "15163545",
            "org_name": "Ab",
            "org_title": "Hakah"
        }
    }
    ]
    }

我使用以下代码打印键和值:

    personMap := make(map[string][]map[string]string)

    json.Unmarshal([]byte(ii), &personMap)


    for key, value := range personMap {
    fmt.Println("index : ", key, " value : ", value){

     }

我得到的输出是:

    index: org value: [map["current":""],map["current":""]

如何在“当前”字段下打印字段的每个值?????

现在我这样做:

    personMap := make(map[string][]struct{Current map[string]string})
    json.Unmarshal([]byte(ii), &personMap)
    for key, value := range personMap {
    fmt.Println("index : ", key, " value : ", value)

    }

我得到的输出是:

    index :  org  value :  [{map[org_dept:Hr org_eptime:1516354574432 org_name:Uejsjak org_title:Hakosklaks]} {map[org_dept:Accounts org_eptime:1516354561184 org_name:Abcd org_title:Hakahkshsjs]}]
    index :  phone  value :  [{map[]} {map[]}]

1 个答案:

答案 0 :(得分:1)

The contents of phone and org are completely different data structures, and you won't be able to cleanly deserialize both into a homogenous format like you've got in the example. The best option is to at least partially deserialize into a struct:

type data struct {
    Phone []map[string]string
    Org []map[string]map[string]string
}

This will at least deserialize all of the data, but it's still a bit messy; a slice of maps of maps is not a great data structure to work with. It's not clear from the question, but if any of the fields are fixed, you might want to codify those in types as well, for example:

type data struct {
    Phone []map[string]string
    Org []struct{
        Current map[string]string
    }
}

You can then deserialize to this type and use it much more easily:

var person data
json.Unmarshal([]byte(ii), &person)
fmt.Printf("%v", person.Phone)
fmt.Printf("%v", person.Org[0].Current)

Working playground example here: https://play.golang.org/p/5W-7RzPimZj

Note that I had to correct an error in the JSON, it is invalid due to a missing comma before "org".