如何解析json对象并打印特定值

时间:2020-02-28 06:50:35

标签: arrays json go marshalling

我有由数组的子对象组成的json对象。如何在json中打印特定的子对象。 这是我的代码

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    //Simple Employee JSON which we will parse
    empArray := `{"meta":[
        {
            "id": 1,
            "name": "Mr. Boss",
            "department": "",
            "designation": "Director"
        },
        {
            "id": 11,
            "name": "Irshad",
            "department": "IT",
            "designation": "Product Manager"
        },
        {
            "id": 12,
            "name": "Pankaj",
            "department": "IT",
            "designation": "Team Lead"
        }
    ]}`

    // Declared an empty interface of type Array
    var results []map[string]interface{}

    // Unmarshal or Decode the JSON to the interface.
    json.Unmarshal([]byte(empArray['meta']), &results)

    fmt.Println(results)
}

我这样做时遇到错误了。

./test.go:35:23: cannot convert empArray['\u0000'] (type byte) to type []byte
./test.go:35:33: invalid character literal (more than one character)

empArray数组对象中,我想打印由员工数组组成的meta对象。请帮我完成这个任务。

2 个答案:

答案 0 :(得分:2)

您快到了。解析整个文档,然后选择所需的部分。

    var results map[string][]interface{}
    json.Unmarshal([]byte(empArray), &results)
    fmt.Println(results["meta"])

答案 1 :(得分:2)

您应该使用自定义结构:

disabledSelection="#{(res.promoName == 'Your String')}"

当您尝试将提供的字符串解组到disabledSelection="#{(res.promoName == 123456)}"变量中时,它将读取注释并知道每个字段的放置位置。您可以在Golang Playground上找到工作示例。我在type Employee struct { ID int `json:"id"` Name string `json:"name"` Department string `json:"department"` Designation string `json:"designation"` } type Employees struct { Meta []Employee `json:"meta"` } 结构中添加了字符串表示形式,以便使Employees的输出更可重用。

在具有额外的嵌套键(Employee)的情况下,类型如下:

fmt.Println

您也可以在Golang Playground上找到工作示例。

注意::我没有上下文来正确命名结构,因此我使用了{meta: {data: [...]}}type Employee struct { ID int `json:"id"` Name string `json:"name"` Department string `json:"department"` Designation string `json:"designation"` } type EmployeesData struct { Data []Employee `json:"data"` } type Employees struct { Meta EmployeesData `json:"meta"` } ,但是您应该使用更具描述性的名称,以帮助理解整个结构对象不仅代表元字段和数据字段。