go - 具有更改键值的多级 Unmarshall JSON

标签 go struct unmarshalling

我看过一些帖子,例如 this one解决了在不同键上解码的问题。但是,当我有多个图层时,我似乎很难弄清楚如何去做。

这是我想解码的内容:
{"chainlink":{"usd":3.75}}然而,chainlinkusd可能会有所不同。

我目前的方法如下所示:

type cryptoCurrency struct {
    Currency cryptoCurrencyResult `json: "chainlink,JPY,gold,apple"`
}

type cryptoCurrencyResult struct {
    Usd float64 `json: "usd,USDT,peso"`
}

(以上显然是错误的)

然后使用它们:
var crypto cryptoCurrency
json.Unmarshal(data, &crypto)

但同样,数据可能看起来像:
{"chainlink":{"usd":3.75}}
{"JPY":{"USDT":1000}}
{"gold":{"peso":100}}
{"apple":{"usd":1.35}}

目前关于 SO 的解决方案似乎是单级解码。

最佳答案

我的一些假设/建议:

  • 您不应该丢失有关加密类型的数据,即它是链环、日元、黄金还是苹果。
  • 您可能还需要考虑货币,然后在程序中将所有内容转换为标准货币。 (我的解决方案中以美元为标准)
  • 我还假设您的 JSON 结构仅限于您在示例中显示的内容。如果有更多的键,解决方案(当然)会改变一点。

  • 您可以为结构使用自定义解码,如下所示:
    type cryptoCurrency struct {
        Type       string
        PriceInUSD float64
    }
    
    func (c *cryptoCurrency) UnmarshalJSON(data []byte) error {
        var tmp map[string]map[string]float64
        json.Unmarshal(data, &tmp)
        for k, v := range tmp {
            c.Type = k
            switch {
            case v["usd"] != 0.0:
                c.PriceInUSD = v["usd"]
            case v["USDT"] != 0.0:
                // Convert into USD... same for peso
            }
        }
        return nil
    }
    

    这是 go playground 中的工作示例.

    关于go - 具有更改键值的多级 Unmarshall JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61784329/

    相关文章:

    java - 我想通过解码将 XML 转换为 Java

    json - panic : json: cannot unmarshal array into Go value of type main. 结构

    arrays - 将[] byte数组转换为uintptr

    html - 如何在 Gin 上返回 html?

    c++ pthreads和struct的损坏数据

    c++ - 从 C++ 中的初始化列表进行 C 风格的结构初始化

    go - 如何使用 proxy.ModifyResponse?

    c++ - 为什么在使用 8 个生产者 1 个消费者进行测试时,golang channel 比 intel tbb concurrent_queue 快得多

    c - 项目帮助 : Function and Struct issues in C?

    json - 出现错误 : math/big: cannot unmarshal into a *big. Int