gpt4 book ai didi

json - 在golang中解析没有索引名称的json

转载 作者:IT王子 更新时间:2023-10-29 00:59:13 26 4
gpt4 key购买 nike

我有一个格式如下的json

{
"status_code": 200,
"status_message": "OK",
"response": {
"Messages": [
"CODE_NOT_AVAILABLE"
],
"UnknownDevices": {
"": [
"6",
"7",
"8",
"9",
"10"
]
}
}
}

正如我们所见,我们缺少一个索引键,在 unknownDevices 之后,我正尝试以下列方式使用 golan 解码此 json

package main

import (
"encoding/json"
"fmt"
)

type pushWooshResponse struct {
Status int `json:"status_code"`
Status_msg string `json:"status_message"`
Response response
}

type response struct {
Message []string `json:"Messages"`
UnknownDevices devices
}

type devices struct {
Udevices []string `json:""`
}

func main() {
itemInfoR := `{"status_code":200,"status_message":"OK","response":{"Messages":["CODE_NOT_AVAILABLE"],"UnknownDevices":{"devices":["6","7","8","9","10"]}}}`
itemInfoBytes := []byte(itemInfoR)
var ItemInfo pushWooshResponse
er := json.Unmarshal(itemInfoBytes, &ItemInfo)
if er != nil {
fmt.Println("Error", er.Error())
} else {
fmt.Println(ItemInfo)
}
}

输出是

{200 OK {[CODE_NOT_AVAILABLE] {[]}}}

除最后一部分外,一切正常,我无法对此进行解码。你能帮我整理 json 的最后一部分吗?

最佳答案

可能还有其他选择,但是每当您看到奇怪的 JSON 时,您总是可以回退到通过实现 json.Unmarshaler 来实现您自己的自定义(未)编码。和/或 json.Marshaler .

也许是这样的:

type devices struct {
Udevices []string
}

func (d *devices) UnmarshalJSON(b []byte) error {
var x map[string][]string
err := json.Unmarshal(b, &x)
if err == nil {
// perhaps check that only a single
// key exists in the map as well
d.Udevices = x[""]
}
return err
}

func (d devices) MarshalJSON() ([]byte, error) {
x := map[string][]string{"": d.Udevices}
return json.Marshal(x)
}

Playground

关于json - 在golang中解析没有索引名称的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122902/

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