【问题标题】:How to read JSON with unknown key in ReasonML?如何在 ReasonML 中读取带有未知键的 JSON?
【发布时间】:2021-03-11 01:01:50
【问题描述】:

我正在编写一个简单的应用程序来显示来自Dog API 的狗图像。我用 bs-json 把它做成记录,以后再用。品种列表可通过 API 获取。响应如下所示。

{
 "message": {
  "breed": ["array of sub-breeds"],
  "breed without subbreed": [],
  ...
  },
"status": "success"
}

所以在编译时密钥是未知的。如果我一个一个添加,那将是某种硬编码。我只想要品种而不是亚品种。如果可能的话,我想要一个数组。

[| "chihuahua", "golden retreiver", ... |] // Something like this so I can make a select input

【问题讨论】:

    标签: reason bucklescript rescript bs-json


    【解决方案1】:

    我认为您可以直接解码为Js.Dict.t,然后获取其密钥。

    类似:

    let decodeBreeds: Js.Json.t => array(string) =
      Json.Decode.(dict(id) |> map(Js.Dict.keys))
    

    【讨论】:

    • 我在对象上使用并得到 [| “消息”、“状态”、“代码”|]。
    • 这只是为了解码品种对象。如果您只想从中获取品种,可以在外部对象上使用 field("message", decodeBreeds)
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多