gpt4 book ai didi

json - 在 Go 中合并动态数据结构

转载 作者:IT王子 更新时间:2023-10-29 00:42:05 28 4
gpt4 key购买 nike

我有这个传入的有效负载,我无法更改。

{
"source": "some random source",
"table": "hosts_table",
"data": [
["address", "id", "services_with_info"],
["0.0.0.1", 1111, [
["service_3", "is very cool", 1],
["service_4", "is very cool", 2]
]
],
["0.0.0.2", 2222, [
["service_3", "is very cool", 3],
["service_4", "is very cool", 4]
]
]
]}

我需要获取“数据”的第一个索引并创建一个新的 JSON 对象,看起来像这样......

"data": [{
"address": "0.0.0.1",
"id": 1111,
"services_with_info":[
{
"service_name": "service_1",
"service_message": "is very cool",
"service_id": 1
},
{...}
]},
{...}]

然后从中构建一个[]Host,数据结构为 5k“hosts”长。我能够将其映射到结构,但需要先将其转换为这种格式。我了解如何解码 JSON,但前提是我可以将有效负载转换为上述内容。

最佳答案

您可以为此使用 json.Unmarshal 并根据您的条件解析数据。我只是为 "data" 做这件事,你也可以为 "services_with_info"

做同样的事情
b := []byte(`{
"source": "some random source",
"table": "hosts_table",
"data": [
["address", "id", "services_with_info"],
["0.0.0.1", 1111, [
["service_3", "is very cool", 1],
["service_4", "is very cool", 2]
]
],
["0.0.0.2", 2222, [
["service_3", "is very cool", 3],
["service_4", "is very cool", 4]
]
]
]}`)
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil {
fmt.Println(err)
return
}
m := f.(map[string]interface{})
result := make(map[string]interface{})
results := make(map[string][]map[string]interface{})
for k, v := range m {
if k == "data" {
s := v.([]interface{})
header := make([]interface{}, 3)
for i, u := range s {
if i == 0 {
header = u.([]interface{})
} else {
row := u.([]interface{})
for j, k := range header {
result[k.(string)] = row[j]
}
results["data"] = append(results["data"], result)
}
}
}
}
fmt.Println(results)

这里的"results"是需要的"data"

关于json - 在 Go 中合并动态数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597143/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com