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

在golang中解析没有索引名的json,json,go,Json,Go,我有一个json,格式如下 { "status_code": 200, "status_message": "OK", "response": { "Messages": [ "CODE_NOT_AVAILABLE" ], "UnknownDevices": { "": [ "6", "7",

我有一个json,格式如下

{
    "status_code": 200,
    "status_message": "OK",
    "response": {
        "Messages": [
            "CODE_NOT_AVAILABLE"
        ],
        "UnknownDevices": {
            "": [
                "6",
                "7",
                "8",
                "9",
                "10"
            ]
        }
    }
}
正如我们所看到的,在未知设备之后,我们缺少了一个索引键,我正试图通过以下方式使用goland来解组这个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] {[]}}}

除了最后一部分,一切都很好,我无法解开它。你能帮我解释一下umarshal json的最后一部分吗。

可能还有其他选择,但每当你看到奇怪的json时,你总是可以通过实现和/或来实现自己的自定义(un)编组

也许是这样的:

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)
}

这个json来自哪里?你真的无法控制吗?空钥匙只是自找麻烦。我建议将未知设备设置为数组而不是对象。空字符串是JSON中的有效键。确保编组方法是无损的。此外,在示例代码中,空键为
devices
。为什么?在您的示例代码中,您有key
设备
,所以您只需要添加标记,试试这个:@RoninDev我想他被json中的空键卡住了。如果他能改变json,这很容易。不幸的是,在我看来,
encoding/json
可以封送空键,但由于某些原因,无法将其解封。请参阅编辑:它也不会封送它们。某些(现已删除)答案更改了
Udevices
字段的类型。相反,您可以像这样实现
json.Unmarshaller
(您还可以实现自定义封送拆收器)。可能会有更好的解决方案。当我尝试这样的方法时,它不起作用,但是,下面的方法行得通。golang.org/p/ut5d5br16您已经更改了JSON的结构,因此需要调整解组以处理该问题。你的问题是关于解封
“”:…
哦,好的,明白了。原因是我将json作为字符串获取,因此我无法更改它,需要解析它。当然,让我看看如何调整解组。非常感谢@DaveAlso。很抱歉,我发送了错误的代码。输入看起来是这样的。很抱歉混淆了如果只是一个空字符串数组,那么“json”响应将如何解组如下内容[“some”、“som2”、“som3”]