You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reason语言中如何将JSON数组转换为list(string)类型?

解决JSON数组转list(string)的问题

错误原因分析

你当前的代码存在两个核心问题:

  1. Belt.Array.map参数顺序错误:Belt库的函数遵循数据后置的设计规范,正确调用顺序应为Belt.Array.map(数组, 处理函数),你误将处理函数放在了参数首位。
  2. 未处理option类型结果:Js.Json.decodeString返回的是option(string)类型,直接map后得到的是array(option(string)),还需过滤掉None值、提取Some中的字符串,再转换为list类型。

修正后的代码

let decodeWords = (json: Js.Json.t): list(string) =>
  switch (Js.Json.decodeArray(json)) {
  | None => []
  | Some(array) =>
    array
    |> Belt.Array.map(Js.Json.decodeString)
    |> Belt.Array.keepMap(option => option)
    |> Belt.List.fromArray
  };

代码细节解释

  • Belt.Array.map(array, Js.Json.decodeString):将数组内的每个JSON元素转换为option(string),得到array(option(string))。
  • Belt.Array.keepMap(option => option):过滤数组中的None值,同时提取Some包裹的字符串,得到纯字符串数组array(string)。
  • Belt.List.fromArray:将最终的字符串数组转换为list(string)类型,满足需求。

简洁写法参考

如果习惯使用管道操作符,也可以用更紧凑的逻辑实现:

let decodeWords = (json: Js.Json.t): list(string) =>
  Js.Json.decodeArray(json)
  |> Option.map(array =>
       array
       |> Belt.Array.filterMap(Js.Json.decodeString)
       |> Belt.List.fromArray
     )
  |> Option.default([]);

这里用Option.map处理数组解码成功的分支,Belt.Array.filterMap一步完成映射与过滤操作,最后用Option.default指定解码失败时的默认空列表。

内容的提问来源于stack exchange,提问作者Knows Not Much

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:55:11