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

我有包含数组子对象的 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包含员工数组的对象。请帮我完成这个。


德玛西亚99
浏览 512回答 2
2回答

慕尼黑8549860

你快到了。解析整个文档,然后挑选出你想要的部分。    var results map[string][]interface{}    json.Unmarshal([]byte(empArray), &results)    fmt.Println(results["meta"])

慕盖茨4494581

您应该使用自定义结构: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您应该使用更具描述性的名称,以帮助理解整个对象所代表的内容,而不仅仅是元和数据字段。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go