Home > front end >  Access data json in golang
Access data json in golang

Time:12-30

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?

CodePudding user response:

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

  • Related