如何获取/提取 JSON 的值



我正在尝试获取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:接口

转换:接口 {} 为零,而不是 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 的说法,它是一个slice而不是一个map所以你需要把它转换为[]interface{}

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"].([]interface{})
for key, value := range products {
// Each value is an interface{} type, that is type asserted as a string
fmt.Println(key, value)
}

最新更新