登录
首页 >  Golang >  Go问答

使用 json.NewDecoder 解析 json 数组

来源:stackoverflow

时间:2024-02-11 15:00:23 291浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《使用 json.NewDecoder 解析 json 数组》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

如何使用 json.newdecoder 将 json 数组(json 文件中的命名列表)获取到列表?我的结构如下所示:

type config struct {
    data1 struct {
        host string `json:"host"`
        port string `json:"port"`
    } `json:"data1"`

    data2 struct {
        host string `json:"host"`
        port string `json:"port"`
    } `json:"data2"`

    list struct {
        items []string
    } `json:"list"`
}

我是这样解析的:

jsonparser := json.newdecoder(configfile)
jsonparser.decode(&config)

我的 config.json 看起来像这样

{
  "data1": {
    "host": "10.10.20.20",
    "port": "1234"
  },
  "data2": {
    "host": "10.10.30.30",
    "port": "5678"
  },
  "list": [
    "item 1",
    "item 2",
    "item 3",
    "item 4"
  ]
}

当字段有名称时很容易,但我不知道如何从列表中获取信息...


正确答案


我找到了解决您问题的方法。这是代码:

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type ConfigWithoutList struct {
    Data1 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data1"`

    Data2 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data2"`
}

type Config struct {
    ConfigWithoutList
    List struct {
        Items []string
    } `json:"list"`
}

func (u *Config) UnmarshalJSON(data []byte) error {
    aux := struct {
        List []string `json:"list"`
        ConfigWithoutList
    }{}
    if err := json.Unmarshal(data, &aux); err != nil {
        return err
    }
    u.List = struct {
        Items []string
    }{
        Items: aux.List,
    }
    return nil
}

func main() {
    const jsonStream = `{
  "data1": {
    "host": "10.10.20.20",
    "port": "1234"
  },
  "data2": {
    "host": "10.10.30.30",
    "port": "5678"
  },
  "list": [
    "item 1",
    "item 2",
    "item 3",
    "item 4"
  ]
}
`
    config := Config{}
    jsonParser := json.NewDecoder(strings.NewReader(jsonStream))
    jsonParser.Decode(&config)

    fmt.Println(config.List) // output => {[item 1 item 2 item 3 item 4]}
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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