Sebastian J
Sebastian J

Reputation: 325

Golang unmarshal json list

I've been struggling to parse a basic array response.

My input JSON, has a list of consistent types of structures.

[
{
  "amount":"6.40000000",
  "date":"1439165701",
  "price":"350.26",
  "tid":104159
},
{
  "amount":"0.10025000",
  "date":"1439162764",
  "price":"351.03",
  "tid":104150
}
]

My struct has a nested array struct.

type TransactionResponse struct {
    Transaction []Transaction
}
type Transaction struct {
    Amount string `json:"amount"`
    Date   string `json:"date"`
    Price  string `json:"price"`
    tid    uint   `json:"tid"`
}

Function to parse the json:

func main() {
    var transactions TransactionResponse

    body, err := http.Get(url)
    err = json.Unmarshal(body, &transactions)
}

Where am I going wrong?

Upvotes: 2

Views: 20233

Answers (2)

Sebastian J
Sebastian J

Reputation: 325

So yes, it took a while...

The TransactionResponse is not a struct type. If I make it a Transaction array, it works as it should.

package main

import (
    "encoding/json"
    "fmt"
)

var body = `[
{
"amount":"6.40000000",
"date":"1439165701",
"price":"350.26",
"tid":104159
},
{
"amount":"0.10025000",
"date":"1439162764",
"price":"351.03",
"tid":104150
}
]
`

type TransactionResponse []Transaction

type Transaction struct {
    Amount string `json:"amount"`
    Date   string `json:"date"`
    Price  string `json:"price"`
    Tid    uint   `json:"tid"`
}

func main() {
    var transactions TransactionResponse

    err := json.Unmarshal([]byte(body), &transactions)
    if err != nil {
        panic(err)
    }

    fmt.Println(transactions)
}

Upvotes: 3

Thundercat
Thundercat

Reputation: 121199

Decode to a slice of transactions:

body, err := http.Get(url)
var transactions []Transaction
err = json.Unmarshal(body, &transactions)

Also, export all of the fields:

type Transaction struct {
  Amount string `json:"amount"`
  Date   string `json:"date"`
  Price  string `json:"price"`
  Tid    uint   `json:"tid"`
}

playground example

Upvotes: 16

Related Questions