为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 中解析结构化数据

在 golang 中解析结构化数据

Go
鸿蒙传说 2022-10-24 15:36:34
我有一个格式良好的字节数组,它的行和列如下(请注意,列用空格分隔)。保证列名和顺序:NAME       UUID                                  TYPE      DEVICE WAN        6a62d79f-fba2-45b3-a3dd-e847c4706d96  ethernet  ens18  DMZ        46a55117-b545-407e-af6e-25d48dfe95f5  ethernet  ens21  LAN        1691607b-9b73-46ff-95c4-9652d062706a  ethernet  ens19  MGT        a4819491-243c-4e5b-8cef-a49de5a9cb07  ethernet  ens22  Untrusted  0734a0ea-c242-4333-bece-2b5cb16e3337  ethernet  ens20 我想遍历每一行并填充如下结构:type Device struct {    connectionID string    uuid         string    deviceType   string    deviceName   string}解决这个问题的最佳方法是什么?
查看完整描述

2 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

所以,如果它是一个字符串,可能应该使用 split 将字符串转换为一个数组,那么由于每一行都有相同的列,那么你很可能通过循环遍历新创建的数组来创建一个结构数组(创建每一行结构在循环期间的每 4 次循环中),那么您将拥有一个定义明确的结构数组,您可以查询和操作。我还没有把代码放上去,因为我只是想确保它实际上是一个像下面这样的字符串?


"NAME       UUID                                  TYPE      DEVICE 

 WAN        6a62d79f-fba2-45b3-a3dd-e847c4706d96  ethernet  ens18  

 DMZ        46a55117-b545-407e-af6e-25d48dfe95f5  ethernet  ens21  

 LAN        1691607b-9b73-46ff-95c4-9652d062706a  ethernet  ens19  

 MGT        a4819491-243c-4e5b-8cef-a49de5a9cb07  ethernet  ens22  

 Untrusted  0734a0ea-c242-4333-bece-2b5cb16e3337  ethernet  ens20"


查看完整回答
反对 回复 2022-10-24
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

我想我会为上面写的评论添加代码:


type Device struct {

    connectionID   string

    uuid           string

    deviceType     string

    deviceName     string

}


type Devices []Device


// getNetworkConnections retrieves a list of network connections and their associated details.

// Details include: connection name, uuid, type, and device id (aka NIC name).

func getNetworkConnections() Devices {

    nmcliCmd := exec.Command("nmcli", "con", "show")

    cmdOutput, err := nmcliCmd.Output()

    if err != nil {

        log.Fatal(err)

    }


    // Iterate through the devices and populate the type.

    var device Device


    rows := strings.Split(string(cmdOutput[:]), "\n") // Create an array of rows containing the output

    for _, row := range rows[1:] {                    // Skip the heading row and iterate through the remaining rows

        cols := strings.Fields(row) // Extract each column from the row.

        if len(cols) == 4 {

            device.connectionID = cols[0]

            device.uuid = cols[1]

            device.deviceType = cols[2]

            device.deviceName = cols[3]

            devices = append(devices, device)

        }

    }


    return devices

}


查看完整回答
反对 回复 2022-10-24
  • 2 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号