为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
德玛西亚99 2022-05-18 15:38:13
我有包含数组子对象的 json 对象。如何在 json 中打印特定的子对象。这是我的代码package mainimport (    "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 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

你快到了。解析整个文档,然后挑选出你想要的部分。


    var results map[string][]interface{}

    json.Unmarshal([]byte(empArray), &results)

    fmt.Println(results["meta"])


查看完整回答
反对 回复 2022-05-18
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您应该使用自定义结构:


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"`

}

当您尝试将提供的字符串解组为Employeesvar 时,它将读取注释并知道每个字段的放置位置。您可以在Golang Playground找到工作示例。我在结构中添加了一个字符串表示,Employee以便fmt.Println输出更可红色。


在有一个额外的嵌套键 ( {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"`

}

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


注意:我没有正确命名结构的上下文,因此我使用了Employees并且EmployeesData您应该使用更具描述性的名称,以帮助理解整个对象所代表的内容,而不仅仅是元和数据字段。


查看完整回答
反对 回复 2022-05-18
  • 2 回答
  • 0 关注
  • 501 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号