登录
首页 >  Golang >  Go问答

如何对下列JSON数组进行解析

来源:stackoverflow

时间:2024-02-22 15:06:26 412浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《如何对下列JSON数组进行解析》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

{
    "machines": [{
        "name": "relay_1",
        "totalmem": "3g",
        "machinemem": "6g"
    }, {
        "name": "relay_2",
        "totalmem": "30g",
        "machinemem": "4g"
    }]
}

尝试使用以下代码进行解析

Run: func(cmd *cobra.Command, args []string) {
                fmt.Println("relay called")
                conf, _ = rootCmd.Flags().GetString("conf")
                if conf != "" {
                        fmt.Println("From Create Command : ", conf)
                }
                data, err := ioutil.ReadFile("file.txt") // data has type []byte
                if err != nil {
                        log.Fatal(err)
                }
                var result []map[string]interface{}
                json.Unmarshal(data, &result)
                relays := result["relays"].(map[string]interface{})
                for key, relay := range relays {
                        fmt.Println("name :", relay["name"],
                                "totalmem:", relay["totalmem"],
                                "relaymem:", relay["relaymem"])

                }
        },

但是我收到如下错误,表明该类型无效

cmd/create_relay.go:54:29:无效类型断言:结果["relays"].(map[string])(左侧为非接口类型map[string]interface {})

有人可以告诉我如何使用下面的接口解析下面的json


解决方案


它适用于以下代码。

type relays struct {
    relays []relay `json:"relays"`
}

type relay struct {
    name       string `json:"name"`
    totalmem   string `json:"totalmem"`
    relaymem   string    `json:"relaymem"`
}

// relaycmd represents the relay command
var createrelaycmd = &cobra.command{
        use:   "relay",
        short: "a brief description of your command",
        long: `a longer description that spans multiple lines and likely contains examples
and usage of using your command. for example:

cobra is a cli library for go that empowers applications.
this application is a tool to generate the needed files
to quickly create a cobra application.`,
        run: func(cmd *cobra.command, args []string) {
                fmt.println("relay called")
                conf, _ = rootcmd.flags().getstring("conf")
                if conf != "" {
                        fmt.println("from create command : ", conf)
                        jsonfile, err := os.open(conf)
                        // if we os.open returns an error then handle it
                        if err != nil {
                                fmt.println(err)
                        }
                        fmt.println("successfully opened users.json")
                        // defer the closing of our jsonfile so that we can parse it later on
                        defer jsonfile.close()
                        data, err := ioutil.readall(jsonfile) // data has type []byte
                        if err != nil {
                                log.fatal(err)
                        }
                        var relays relays
                        json.unmarshal(data,&relays)
                        for i := 0; i < len(relays.relays); i++ {
                                fmt.println("user name: " + relays.relays[i].name)
                                fmt.println("user totalmem: " + relays.relays[i].totalmem)
                                fmt.println("user relaymem: " + relays.relays[i].relaymem)
                        }
                }
        },
}

代码中的result是一个地图数组,而您使用的是无效的result["relays"]

你的代码应该是这样的:

Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("relay called")
            conf, _ = rootCmd.Flags().GetString("conf")
            if conf != "" {
                    fmt.Println("From Create Command : ", conf)
            }
            data, err := ioutil.ReadFile("file.txt") // data has type []byte
            if err != nil {
                    log.Fatal(err)
            }
            var result map[string]interface{}
            json.Unmarshal(data, &result)
            relays := result["relays"].([]interface{})
            for _, relay := range relays {
                    relayM := relay.(map[string]interface{})
                    fmt.Println("name :", relayM["name"].(string),
                            "totalmem:", relayM["totalmem"].(string),
                            "relaymem:", relayM["relaymem"].(string))

            }
    },

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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