我是Go语言的初学者。我正在尝试获取Json的值/索引/键,但没有成功。我找到了一些答案和教程,但无法让它们为我工作。
我有以下Json:
{
"id": "3479",
"product": "Camera",
"price": "",
"creation": 04032020,
"products": [
{
"camera": "Nikon",
"available": true,
"freeshipping": false,
"price": "1,813",
"color": "black"
},
{
"camera": "Sony",
"available": true,
"freeshipping": true,
"price": "931",
"color": "black"
}
],
"category": "eletronics",
"type": "camera"
}
我尝试了几个示例,但没有一个适用于这种类型的Json。
我得到的错误:
panic:接口转换:interface {}为nil,不是map [string] interface {}
[我相信是由于"products[]"
我尝试了map[string]interface{}
和[]interface{}
,所以它可以编译,但后来给了我这个错误。
您能举例说明如何提取这些值吗?谢谢。
我正在使用的代码:
//gets the json
product,_:=conn.GetProductData(shop.Info.Id)
// assing a variable
productInformation:=<-product
//prints the json
fmt.Printf(productInformation)
//try to get json values
type Product struct {
Id string
Product string
}
var product Product
json.Unmarshal([]byte(productInformation), &product)
fmt.Printf("Id: %s, Product: %s", product.Id, product.Product)
此代码不会出现紧急情况,但也不会显示所有结果,因此我尝试了下面的这个(应该可以给我所有结果),但是它很着急
var result map[string]interface{}
json.Unmarshal([]byte(productInformation), &result)
// The object stored in the "birds" key is also stored as
// a map[string]interface{} type, and its type is asserted from
// the interface{} type
products := result["products"].(map[string]interface{})
for key, value := range products {
// Each value is an interface{} type, that is type asserted as a string
fmt.Println(key, value.(string))
}
您需要添加json标记以指定json中的字段名称,因为它是小写字母
type Product struct {
Id string `json:"id"`
Product string `json:"product"`
}
并且在第二次访问中,根据json是product
而不是products
并且它是slice
而不是map
,因此您需要将其强制转换为[]interface{}
products := result["product"].([]interface{})