所以我在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
- 1 回答
- 0 關注
- 132 瀏覽
添加回答
舉報
0/150
提交
取消