简体   繁体   English

将逗号分隔的值反序列化为结构体

[英]deserialize comma-separated values into struct

Let's say i have a string like this:假设我有一个这样的字符串:

key1=val1, key2=val2 (and so on) key1=val1, key2=val2(以此类推)

I want to deserialize it into a struct (the type I defined in my code), just like we do with JSON or XML.我想将它反序列化为一个结构体(我在代码中定义的类型),就像我们处理 JSON 或 XML 一样。 Ofc one could write a decoder function, but I thought it may exist, because writing your own deserializer may take some time and before doing it I thought there could be Go's standard library way. Ofc 可以编写一个解码器函数,但我认为它可能存在,因为编写自己的解串器可能需要一些时间,在此之前我认为可能存在 Go 的标准库方式。

Don't know of a library to do what you're asking.不知道图书馆可以做你所要求的。 But it's easy to work with a string like that.但是使用这样的字符串很容易。 If there were just a few types of structs I needed to do that with, I'd use strings.Split(s, ", ") to create a slice of key=value strings, and then strings.Split(ss, "=") again on the pieces, if I wanted to write code quickly that didn't need to be efficient.如果我只需要使用几种类型的结构,我会使用 strings.Split(s, ", ") 创建一个 key=value 字符串片段,然后使用 strings.Split(ss, "= ") 再一次,如果我想快速编写不需要高效的代码。 Then run the key value through a switch statement and update the matching struct field.然后通过 switch 语句运行键值并更新匹配的结构字段。

If I wanted that to be super efficient, I'ld write a loop around the switch statement that reset two byte slices to each subsequent key and value and not bother creating slices of strings first.如果我希望它非常高效,我会围绕 switch 语句编写一个循环,将两个字节的切片重置为每个后续的键和值,而不是先创建字符串切片。

On the other hand, if I wanted to write the code fast, and work with many types of structs, I'd modify the string to be legal JSON and then use the JSON Unmarshal() function.另一方面,如果我想快速编写代码并使用多种类型的结构,我会将字符串修改为合法的 JSON,然后使用 JSON Unmarshal() 函数。 It would be quick to write, and the json.Unmarshal() error would tell you if you had missed anything.编写起来会很快,并且 json.Unmarshal() 错误会告诉您是否遗漏了任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM