为什么我无法使用 Unmarshal 解析具有嵌套数组的 json

Why I can't parse json which has nested array with Unmarshal

我想在 Go 中使用 json.Unmarshal 解析此 json。

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

来源 returns {[]} 关于解析结果。


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)
    // {[]} 
}

我不知道结果的原因。

编辑:正如@mkopriva 指出的那样,如果字段未导出(即以大写字母开头),JSON 将不会解组到结构中,例如

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"`
}

有很多在线 JSON 验证器,例如https://jsonlint.com/

将您的 JSON 粘贴到会显示错误:

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

在第 18 行添加 ] 以完成数组将修复您的 JSON,例如

            "low": "81.79"
        }
    ]
}

我不得不导出。

type GaitameOnlineResponse struct {
    Quotes []Quote
}

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

我解决了。