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

JSON解析为Tree Int输出Nothing,如何解析为Tree Int/String类型?

解析JSON到Haskell的Tree类型问题解决

你的代码返回Nothing是因为Data.Tree的默认FromJSON实例要求JSON是对象结构,而你用了数组格式。

先搞清楚默认实例的JSON结构

Data.Tree定义的Tree a是Node a [Tree a],它的默认FromJSON实例对应的JSON必须是包含两个字段的对象:

  • rootLabel:对应节点的数值/字符串
  • subForest:对应子树组成的数组

比如你想表示Node 1 [Node 2 []],正确的JSON应该是:

{"rootLabel":1,"subForest":[{"rootLabel":2,"subForest":[]}]}

用这个JSON测试你的代码,就能得到Just (Node 1 [Node 2 []]),解析Tree String同理,把数值换成字符串即可。

如果想适配你写的数组格式([值, 子树数组])

需要自定义FromJSON实例,让它支持解析数组形式的JSON:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}

import Data.Aeson
import Data.Aeson.Types (withArray)
import Data.Tree
import Data.Vector (toList)

instance FromJSON a => FromJSON (Tree a) where
  parseJSON = withArray "Tree" $ \arr ->
    case toList arr of
      [valJson, subForestJson] -> 
        Node <$> parseJSON valJson <*> parseJSON subForestJson
      _ -> fail "Tree格式错误:必须是[根节点值, 子树数组]的二元数组"

main :: IO ()
main = do
  -- 解析Tree Int
  print $ decode "[1,[2,[]]]" :: Maybe (Tree Int)
  -- 解析Tree String
  print $ decode "[\"hello\", [\"world\", []]]" :: Maybe (Tree String)

运行这段代码,就能得到预期的Just (Node 1 [Node 2 []])和Just (Node "hello" [Node "world" []])。

内容的提问来源于stack exchange,提问作者F. Zer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:35:19