首页 > 解决方案 > 在 Go 中如何动态解析 JSON?

问题描述

所以我在 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]interface{}但它不起作用。我已经尝试了另一个名为 jsoniter 的第三方库,但它也不起作用。

我可以让它“以某种方式”工作的唯一方法是尝试用括号包裹 json_string [jsonstring]

这是我的代码。

file, _ := ioutil.ReadFile("p1.json")
var results []map[string]interface{}
json.Unmarshal(file, &results)
fmt.Printf("%+v", results) // Output [] 

标签: jsongounmarshalling

解决方案


始终检查错误。从您检查错误json.Unmarshal可以看到:

2009/11/10 23:00:00 json: cannot unmarshal object into Go value of type []map[string]interface {}

您正在使用一片地图[]map[string]interface{}来编组,而不是您想要的地图:

// 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 ...

https://play.golang.org/p/4OpJiNlB27f


推荐阅读