猿问

在 Golang 中创建此 JSON 对象的最佳方法

我正在尝试找到使用 Go 创建此 JSON 对象的最佳方法:


{

  "Clients" : [

    {

      "Hostname" : "example.com",

      "IP" : "127.0.0.1",

      "MacAddr" : "mactonight"

    },

    {

      "Hostname" : "foo.biz",

      "IP" : "0.0.0.0",

      "MacAddr" : "12:34:56:78"

    }

  ]

}

在我现有的代码中,我目前正在分割多个字符串行,然后将每行拆分为 3 个单独的变量(主机、ip、mac)。例如hostname 192.168.1.0 F0:F0:F0:F0:F0被连续转换。


这是通过以下代码完成的:


func parselines(line string){

    for _, line := range strings.Split(line, "\n") {

        if line != "" {

            s := strings.Split(line, " ")

            host, ip, mac := s[0], s[1], s[2]

            fmt.Println("Hostname: " + host + " IP: " + ip + " MAC: " + mac)

        }

    }

}

所以在这个 for 循环中,我希望构建上面提到的 JSON 对象。我已经尝试过使用结构,但我真的很困惑如何使用它们。我已经用 Ruby 完成了这项工作,这需要几行代码,但 Go 似乎非常具有挑战性(对我来说就是这样!)。在红宝石中它是这样完成的:


require 'json'


clients = []


STDIN.each do |line|

  fields = line.split(/\s+/)

  clients << {

    Hostname: fields[0],

    IP: fields[1],

    MacAddr: fields[2]

  }

end


connections = {}

connections[:Clients] = clients

puts connections.to_json


守着一只汪
浏览 460回答 3
3回答

慕桂英4014372

声明与 JSON 文档结构匹配的类型。type client struct {&nbsp; &nbsp; Hostname string `json:"Hostname"`&nbsp; &nbsp; IP&nbsp; &nbsp; &nbsp; &nbsp;string `json:"IP"`&nbsp; &nbsp; MacAddr&nbsp; string `json:"MacAddr"`}type connection struct {&nbsp; &nbsp; Clients []*client `json:"Clients"`}使用这些类型初始化值并编码为 JSON。var clients []*clientfor _, line := range strings.Split(line, "\n") {&nbsp; &nbsp; if line != "" {&nbsp; &nbsp; &nbsp; &nbsp; s := strings.Split(line, " ")&nbsp; &nbsp; &nbsp; &nbsp; clients = append(clients, &client{Hostname: s[0], IP: s[1], MacAddr: s[2]})&nbsp; &nbsp; }}p, _ := json.Marshal(connection{Clients: clients})fmt.Printf("%s\n", p)json:"Hostname"此示例中不需要JSON 字段标记 ( ),因为 JSON 对象键是有效的导出标识符。我在这里包含标签是因为它们经常被需要。

缥缈止盈

创建切片和映射以匹配所需数据的结构。var clients []interface{}for _, line := range strings.Split(line, "\n") {&nbsp; &nbsp; if line != "" {&nbsp; &nbsp; &nbsp; &nbsp; s := strings.Split(line, " ")&nbsp; &nbsp; &nbsp; &nbsp; clients = append(clients, map[string]string{"Hostname": s[0], "IP": s[1], "MAC": s[2]})&nbsp; &nbsp; }}connections := map[string]interface{}{"Clients": clients}p, _ := json.Marshal(connections)fmt.Printf("%s\n", p)

拉丁的传说

您需要初始化 2 个结构type Client struct {&nbsp; &nbsp; Hostname string&nbsp; &nbsp; IP string&nbsp; &nbsp; MacAddr string}type Connection struct {&nbsp; &nbsp; Clients []Client}并使用 Marshal 将 struct 转换为 Jsonvar clients []Clientclients = append(clients, Client{&nbsp; &nbsp; Hostname: "localhost",&nbsp; &nbsp; IP: "127.0.0.1",&nbsp; &nbsp; MacAddr: "1123:22512:25632",})// add more if you want ...myJson, _ := json.Marshal(Connection{Clients:clients})fmt.Println(string(myJson))不要忘记导入这个import "encoding/json"
随时随地看视频慕课网APP

相关分类

Go
我要回答