我的目标是在 Haskell 中编写一个程序,该程序采用 json 文件的名称并将其余参数解释为导航该 json 文件并打印导航到的值的路径。问题是因为 JSON 可以包含多种值类型,我不知道如何让 Haskell 的类型系统理解我想要的。这是我无法正确实现的带有“导航”功能的 Haskell 代码:
import qualified Data.Aeson as A
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.List
import Data.Maybe
import System.Environment
parse :: String -> A.Value
parse = fromJust . A.decode . BSL.pack
isInteger xs = case reads xs :: [(Integer, String)] of
[(_, "")] -> True
_ -> False
navigate :: A.Value -> String -> String
navigate value [] = value
navigate value [x:xs]
| isInteger x = ??? -- value is an array, get the xth element of it.
| otherwise = ??? -- value is an map, x is a key in it.
main :: IO ()
main = do
[filename:path] <- getArgs
contents <- readFile filename
let d = parse contents
putStrLn (show (navigate d path))
作为参考,下面是用 Python 编写相同程序的方式:
from json import load
from sys import argv
def navigate(obj, path):
if not path:
return obj
head, tail = path[0], path[1:]
return navigate(obj[int(head) if head.isdigit() else head], tail)
if __name__ == '__main__':
fname, path = argv[1], argv[2:]
obj = load(open(fname))
print navigate(obj, path)
该程序将像这样运行:
$ cat data.json
{"foo" : [[1, 2, 3, {"bar" : "barf"}]]}
$ python showjson.py data.json foo 0 3 bar
barf