gpt4 book ai didi

json - Golang - 使用更改键值解码 JSON

转载 作者:IT王子 更新时间:2023-10-29 01:51:06 29 4
gpt4 key购买 nike

我正在尝试将 JSON 解码为一个结构,但事实证明这很困难,因为外部 JSON 键发生了变化,而我一周前才开始。这是我的手动尝试:

import (
"encoding/json"
"fmt"
"strconv"
)

type Device struct {
localUUID string
applicationUUID string
externalUUID string
commit string
lastSeen string
state string
progress float32
}

func main() {
devices := make([]*Device, 0, 10)

b := []byte(`{
"5417871461137421886": {
"applicationUUID": "test_applicationUUID",
"commit": "test_commit",
"lastSeen": "test_lastSeen",
"localUUID": "E4:F5:13:8E:F5:43",
"progress": "3.5",
"externalUUID": "test_externalUUID",
"state": "test_state"
},
"5632882567440442530": {
"applicationUUID": "test_applicationUUID",
"commit": "test_commit",
"lastSeen": "test_lastSeen",
"localUUID": "E4:F5:13:8E:F5:42",
"progress": "3.5",
"externalUUID": "test_externalUUID",
"state": "test_state"
},
"8912255216147730520": {
"applicationUUID": "test_applicationUUID",
"commit": "test_commit",
"lastSeen": "test_lastSeen",
"localUUID": "E4:F5:13:8E:F5:41",
"progress": "3.5",
"externalUUID": "test_externalUUID",
"state": "test_state"
}
}`)

var f interface{}
json.Unmarshal(b, &f)
outer := f.(map[string]interface{})
for _, value := range outer {
inner := value.(map[string]interface{})
device := &Device{}
device.localUUID = inner["localUUID"].(string)
device.applicationUUID = inner["applicationUUID"].(string)
device.externalUUID = inner["externalUUID"].(string)
device.commit = inner["commit"].(string)
device.lastSeen = inner["lastSeen"].(string)
device.state = inner["state"].(string)
f, _ := strconv.ParseFloat(inner["progress"].(string), 32)
device.progress = float32(f)

devices = append(devices, device)
}

for _, device := range devices {
fmt.Println(device)
}
}

有没有一种方法可以忽略键并迭代值,从而允许我使用 json.Unmarshal(b, &Device)?

最佳答案

您有一系列 JSON 对象,映射每个 Device 的唯一 ID。将其解码为 map

type Device struct {
LocalUUID string `json:"localUUID"`
ApplicationUUID string `json:"applicationUUID"`
ExternalUUID string `json:"externalUUID"`
Commit string `json:"commit"`
LastSeen string `json:"lastSeen"`
State string `json:"state"`
Progress float32 `json:"progress,string"`
}

func main() {
devices := make(map[string]*Device)

err := json.Unmarshal(b, &devices)
if err != nil {
log.Fatal(err)
}

for _, device := range devices {
fmt.Printf("%#v\n", device)
}
}

https://play.golang.org/p/JDZzG64jJR

关于json - Golang - 使用更改键值解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794336/

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