英文:
Access data json in golang
问题
我有以下的JSON文档:
{
  id: int
  transaction_id: string
  total: string
  line_items: [
    {
      id: int
      name: string
    }
  ]  
}
这是我的代码:
type Order struct {
	ID            int           `json:"id"`
	TransactionId string        `json:"transaction_id"`
	Total         string        `json:"total"`
	LineItems     []interface{} `json:"line_items"`
}
...
var order Order
json.Unmarshal([]byte(sbody), &order)
for index, a := range order.LineItems {
	fmt.Println(a["name"])
}
我得到了错误信息:
invalid operation: cannot index a (variable of type interface{})
我应该创建一个Item结构体吗?
英文:
I have the following JSON document:
{
  id: int
  transaction_id: string
  total: string
  line_items: [
    {
      id: int
      name: string
    }
  ]  
}
This is my code
type Order struct {
	ID            int           `json:"id"`
	TransactionId string        `json:"transaction_id"`
	Total         string        `json:"total"`
	LineItems     []interface{} `json:"line_items"`
}
...
var order Order
json.Unmarshal([]byte(sbody), &order)
for index, a := range order.LineItems {
		fmt.Println(a["name"])
}
I got the error:
invalid operation: cannot index a (variable of type interface{})
Should I create an Item struct?
答案1
得分: 1
将LineItems字段的类型修改为[]map[string]interface{}。
package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	type Order struct {
		ID            int                      `json:"id"`
		TransactionId string                   `json:"transaction_id"`
		Total         string                   `json:"total"`
		LineItems     []map[string]interface{} `json:"line_items"`
	}
	var order Order
	err := json.Unmarshal([]byte(`{
		"id": 1,
		"transaction_id": "2",
		"total": "3",
		"line_items": [
			{
				"id": 2,
				"name": "444"
			}
		]
	}`), &order)
	if err != nil {
		panic(err)
	}
	for _, a := range order.LineItems {
		fmt.Println(a["name"])
	}
}
英文:
Modify the LineItems field type to []map[string]interface{}.
package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	type Order struct {
		ID            int                      `json:"id"`
		TransactionId string                   `json:"transaction_id"`
		Total         string                   `json:"total"`
		LineItems     []map[string]interface{} `json:"line_items"`
	}
	var order Order
	err := json.Unmarshal([]byte(`{
		"id": 1,
		"transaction_id": "2",
		"total": "3",
		"line_items": [
			{
				"id": 2,
				"name": "444"
			}
		]
	}`), &order)
	if err != nil {
		panic(err)
	}
	for _, a := range order.LineItems {
		fmt.Println(a["name"])
	}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论