登录
首页 >  Golang >  Go问答

使用 Golang 解析 JSON 数据

来源:stackoverflow

时间:2024-03-06 09:51:26 122浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用 Golang 解析 JSON 数据》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我有 json 文件

{
    "info": {
        "_postman_id": "ac691afd-f987-47ca-82d3-dae2a367e3df",
        "name": "parsego",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
        {
            "name": "gogo",
            "request": {
                "method": "get",
                "header": [],
                "url": {
                    "raw": "https://www.google.com/",
                    "protocol": "https",
                    "host": [
                        "www",
                        "google",
                        "com"
                    ],
                    "path": [
                        ""
                    ]
                }
            },
            "response": []
        },
        {
            "name": "golang",
            "request": {
                "method": "get",
                "header": [],
                "url": {
                    "raw": ""
                }
            },
            "response": []
        },
        {
            "name": "hide pool!",
            "request": {
                "method": "get",
                "header": [],
                "url": {
                    "raw": ""
                }
            },
            "response": []
        }
    ],
    "protocolprofilebehavior": {}
}

我想解析这个,我想在终端名称和方法中看到。我怎样才能做到这一点?

我尝试了这个但不起作用(请帮忙。我尝试使用此代码

package main
{
import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type Student struct {
    Name     string
    Standard int `json:"Standard"`
}

func main() {
    // open the file pointer
    studentFile, err := os.Open("data.json")
    if err != nil {
        log.Fatal(err)
    }
    defer studentFile.Close()

    var studentDecoder *json.Decoder = json.NewDecoder(studentFile)
    if err != nil {
        log.Fatal(err)
    }

    var studentList []Student

    err = studentDecoder.Decode(&studentList)
    if err != nil {
        log.Fatal(err)
    }

    for i, student := range studentList {
        fmt.Println("Student", i+1)
        fmt.Println("Student name:", student.Name)
        fmt.Println("Student standard:", student.Standard)
    }
}

我的 go 能力不强,我如何修改我的任务的代码,这可能吗?如果我尝试这个代码,我会遇到这个错误 2020/11/05 13:29:54 json:无法将对象解组为 []main.student 类型的 go 值 退出状态1


解决方案


你可以尝试做这样的事情:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type data struct {
    item []item `json:"item"`
}

type item struct {
    name    string  `json:"name"`
    request request `json:"request"`
}

type request struct {
    method string `json:"method"`
}

func main() {
    filename := "/path/to/your_file.json"
    jsonfile, err := os.open(filename)
    if err != nil {
        fmt.printf("failed to open json file: %s, error: %v", filename, err)
        return
    }
    defer jsonfile.close()

    jsondata, err := ioutil.readall(jsonfile)
    if err != nil {
        fmt.printf("failed to read json file, error: %v", err)
        return
    }

    data := data{}
    if err := json.unmarshal(jsondata, &data); err != nil {
        fmt.printf("failed to unmarshal json file, error: %v", err)
        return
    }

    // print
    for _, item := range data.item {
        fmt.printf("name: %s, method: %s \n", item.name, item.request.method)
    }
}

结果必须如下所示:

Name: Gogo, Method: GET
Name: Golang, Method: GET
Name: Hide Pool!, Method: GET

本篇关于《使用 Golang 解析 JSON 数据》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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