Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Go中动态解析JSON?_Json_Go_Unmarshalling - Fatal编程技术网

如何在Go中动态解析JSON?

如何在Go中动态解析JSON?,json,go,unmarshalling,Json,Go,Unmarshalling,所以我在解析Go中的JSON文件时遇到了一些问题。我已经尝试了很多方法来解决这个问题,但我似乎没有找到解决办法 假设我有一个JSON文件,看起来像这样 { "products": [ { "id": 201, "name": "Nulla", "price": 207, &quo

所以我在解析Go中的JSON文件时遇到了一些问题。我已经尝试了很多方法来解决这个问题,但我似乎没有找到解决办法

假设我有一个JSON文件,看起来像这样

{
    "products": [
        {
            "id": 201,
            "name": "Nulla",
            "price": 207,
            "categoryId": 1,
            "rate": 2.44,
            "content": "Culpa sed tenetur incidunt quia veniam sed molliti",
            "review": 78,
            "imageUrl": "https://dummyimage.com/400x350"
        },
        {
            "id": 202,
            "name": "Corporis",
            "price": 271,
            "categoryId": 1,
            "rate": 2.18,
            "content": "Nam incidunt blanditiis odio inventore. Nobis volu",
            "review": 67,
            "imageUrl": "https://dummyimage.com/931x785"
        },
        {
            "id": 203,
            "name": "Minus",
            "price": 295,
            "categoryId": 1,
            "rate": 0.91,
            "content": "Quod reiciendis aspernatur ipsum cum debitis. Quis",
            "review": 116,
            "imageUrl": "https://dummyimage.com/556x985"
        }
    ]
}
我想动态地解析它(而不为它生成结构)。我已经尝试了
map[string]接口{}
的方式,但它不起作用。我已经尝试了另一个第三方库,名为jsoniter,但它不起作用

我能让它“以某种方式”工作的唯一方法是尝试用括号包装json_字符串
[jsonstring]

这是我的密码

文件,Util:=ioutil.ReadFile(“p1.json”)
var results[]映射[string]接口{}
Unmarshal(文件和结果)
fmt.Printf(“%+v”,结果)//输出[]

始终检查错误。检查
json.Unmarshal
中的错误可以看到:

2009/11/10 23:00:00 json: cannot unmarshal object into Go value of type []map[string]interface {}
您正在使用映射片
[]映射[string]接口{}
封送到映射,而不是您想要的映射:

// var results []map[string]interface{} // bad-type
var results map[string]interface{} // correct-type
err := json.Unmarshal(body, &results)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("%+v", results) // Output [map[categoryId:1 content:Culpa sed tenetur incidunt quia veniam sed molliti id:20 ...

始终检查错误
json.Unmarshal(文件和结果)
您应该能够将该json解组到
map[string]接口{}
(而不是
[]map[string]接口{}
)。当你说它不起作用时,发生了什么?您应该检查所有返回的错误。你确定它读取的文件正确吗?我真的很抱歉。我是新手,只是尝试新事物。谢谢你的反馈。我以后一定要检查错误。