亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號