【问题标题】:Parse JSON File in Golang在 Golang 中解析 JSON 文件
【发布时间】:2021-02-17 22:52:09
【问题描述】:

我有 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)
    }
} 

我不擅长围棋,我该如何修改我的任务的代码,这可能吗?如果我尝试这段代码我有这个错误 2020/11/05 13:29:54 json:无法将对象解组为 []main.Student 类型的 Go 值 退出状态 1

【问题讨论】:

标签: json 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

【讨论】:

  • NIT:在延迟 json.Close 之前检查第一个 err 值。
  • @Olshansk 有道理,谢谢!
猜你喜欢
  • 2020-10-26
  • 2021-12-03
  • 2016-02-24
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多