-2

I want parse this json using json.Unmarshal in Go.

{
    "quotes": [
        {
            "high": "1.9981",
            "open": "1.9981",
            "bid": "1.9981",
            "currencyPairCode": "GBPNZD",
            "ask": "2.0043",
            "low": "1.9981"
        },
        {
            "high": "81.79",
            "open": "81.79",
            "bid": "81.79",
            "currencyPairCode": "CADJPY",
            "ask": "82.03",
            "low": "81.79"
        }
    ]
}

source returns {[]} about parse result.


type GaitameOnlineResponse struct {
    quotes []Quote
}

type Quote struct {
    high             string
    open             string
    bid              string
    currencyPairCode string
    ask              string
    low              string
}

func sampleParse() {
    path := os.Getenv("PWD")
    bytes, err := ioutil.ReadFile(path + "/rate.json")
    if err != nil {
        log.Fatal(err)
    }
    var r GaitameOnlineResponse
    if err := json.Unmarshal(bytes, &r); err != nil {
        log.Fatal(err)
    }
    fmt.Println(r)
    // {[]} 
}

I don't know a reason of the result.

Takato Horikoshi
  • 363
  • 5
  • 15

2 Answers2

1

Edit: And as @mkopriva has pointed out the JSON will not unmarshal into the struct, if the fields are not exported (i.e. begin with a capital letter) e.g.

type GaitameOnlineResponse struct {
    Quotes []Quote `json:"quotes"`
}

type Quote struct {
    High             string `json:"high"`
    Open             string `json:"open"`
    Bid              string `json:"bid"`
    CurrencyPairCode string `json:"currencyPairCode"` // add tags to match the exact JSON field names
    Ask              string `json:"ask"`
    Low              string `json:"low"`
}

There's many online JSON validators out there e.g. https://jsonlint.com/

Pasting your JSON into reveals the error:

Error: Parse error on line 17:
..."low": "81.79"

Adding a ] to complete the array at line 18 will fix your JSON e.g.

            "low": "81.79"
        }
    ]
}
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
1

I had to export.

type GaitameOnlineResponse struct {
    Quotes []Quote
}

type Quote struct {
    High             string
    Open             string
    Bid              string
    CurrencyPairCode string
    Ask              string
    Low              string
}

I resolved.

Takato Horikoshi
  • 363
  • 5
  • 15