在golang中解析结构化数据

huangapple go评论79阅读模式
英文:

Parsing structured data in golang

问题

你可以按行分割字节数组,并使用空格分割每一行的列。然后,你可以使用分割后的列值来填充结构体的字段。以下是一个示例代码:

package main

import (
	"fmt"
	"strings"
)

type Device struct {
	connectionID string
	uuid         string
	deviceType   string
	deviceName   string
}

func main() {
	byteArray := []byte(`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`)

	rows := strings.Split(string(byteArray), "\n")

	// Iterate over each row (excluding the header)
	for i := 1; i < len(rows); i++ {
		columns := strings.Fields(rows[i])

		// Populate the Device struct fields
		device := Device{
			connectionID: columns[0],
			uuid:         columns[1],
			deviceType:   columns[2],
			deviceName:   columns[3],
		}

		// Do something with the populated struct
		fmt.Printf("%+v\n", device)
	}
}

这段代码将字节数组按行分割,并迭代每一行(不包括标题行)。然后,它使用空格分割每一行的列,并将列值填充到 Device 结构体的字段中。你可以根据需要修改代码来处理填充后的结构体。

英文:

I have a well-formatted byte array that has rows and columns as follows (note that the columns are separated by spaces). The column names and order are guaranteed:

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 

I would like to iterate over each row and populate a structure as follows:

type Device struct {
	connectionID string
	uuid         string
	deviceType   string
	deviceName   string
}

What is the best way to approach this?

答案1

得分: 1

所以,如果它是一个字符串,可能应该使用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"
英文:

So, if it's a string, probably should use split to turn the string into an array, then since each row has the same columns, then you might very well create an array of struct by looping through that newly made array (create each row struct during every 4 times cycle during the loop), then you will have a well defined array of struct that you can query and manipulate. I haven't put the code up yet, because I just want to make sure it's actually a string like following?

&quot;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&quot;

答案2

得分: 0

我认为我应该添加上面我写的评论的代码:

type Device struct {
    connectionID string
    uuid         string
    deviceType   string
    deviceName   string
}

type Devices []Device

// getNetworkConnections检索网络连接及其相关详细信息的列表。
// 详细信息包括:连接名称、uuid、类型和设备ID(也称为NIC名称)。
func getNetworkConnections() Devices {
    nmcliCmd := exec.Command("nmcli", "con", "show")
    cmdOutput, err := nmcliCmd.Output()
    if err != nil {
        log.Fatal(err)
    }

    // 遍历设备并填充类型。
    var devices Devices

    rows := strings.Split(string(cmdOutput[:]), "\n") // 创建包含输出的行数组
    for _, row := range rows[1:] {                    // 跳过标题行并遍历剩余行
        cols := strings.Fields(row) // 从行中提取每列。
        if len(cols) == 4 {
            device := Device{
                connectionID: cols[0],
                uuid:         cols[1],
                deviceType:   cols[2],
                deviceName:   cols[3],
            }
            devices = append(devices, device)
        }
    }

    return devices
}
英文:

I thought I would add the code for the comment I wrote above:

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(&quot;nmcli&quot;, &quot;con&quot;, &quot;show&quot;)
	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[:]), &quot;\n&quot;) // 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
}

huangapple
  • 本文由 发表于 2022年1月9日 10:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70637936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定