为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Go 中动态解析 JSON?

如何在 Go 中动态解析 JSON?

Go
弑天下 2022-08-24 11:25:37
所以我在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 [] 
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

始终检查错误。检查错误,您可以看到以下内容: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


查看完整回答
反对 回复 2022-08-24
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号