猿问

如何在 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"

        }

    ]

}

我想动态解析它(不为它制作结构)。我已经尝试过方式,但它不起作用。我已经尝试了另一个名为jsoniter的第三方库,但它也不起作用。map[string]interface{}


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


这是我的代码。


file, _ := ioutil.ReadFile("p1.json")

var results []map[string]interface{}

json.Unmarshal(file, &results)

fmt.Printf("%+v", results) // Output [] 


弑天下
浏览 121回答 1
1回答

鸿蒙传说

始终检查错误。检查错误,您可以看到以下内容:json.Unmarshal2009/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-typevar results map[string]interface{} // correct-typeerr := 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
随时随地看视频慕课网APP

相关分类

Go
我要回答