登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-08 10:21:35 150浏览 收藏

你在学习Golang相关的知识吗?本文《如何解析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 对象。请帮助我完成这个任务。


解决方案


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

var results map[string][]interface{}
    json.unmarshal([]byte(emparray), &results)
    fmt.println(results["meta"])

您应该使用自定义结构:

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 var 中时,它将读取注释并知道每个字段的放置位置。您可以在 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 找到工作示例。

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

今天关于《如何解析json对象并打印特定值》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>