亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號