在Golang中访问JSON数据。

huangapple go评论68阅读模式
英文:

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"])
	}
}

huangapple
  • 本文由 发表于 2022年12月30日 02:07:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/74954613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定