可以使用GHCI中的json包解析JSON,但不能在使用GHC编译时解析

时间:2021-09-03 17:04:54

I'm trying to parse a JSON string using the json library. This code works perfectly in GHCI:

我正在尝试使用json库解析JSON字符串。此代码在GHCI中完美运行:

import Text.JSON as JS
JS.decode  "{}"  :: Result JSValue

But when I use the same code in a compiled program:

但是当我在编译的程序中使用相同的代码时:

case JS.decode "{}" of
  JS.Ok value -> putStrLn value
  JS.Error err -> error err

It is unable to parse the String with:

它无法解析String:

Unable to read String

I suspect it's just me doing something stupid but I can't figure out what....

我怀疑这只是我做了一些愚蠢的事情,但我无法弄清楚是什么......

Any ideas very very welcome!

任何想法都非常欢迎!

Update:

I wrote this code to see if it was something in the other part of the app causing the problem:

我编写了这段代码,看看它是否是应用程序其他部分引起问题的原因:

import qualified Text.JSON as JS

main :: IO ()
main = do
   case JS.decode "{}" of
                JS.Ok value -> putStrLn value
                JS.Error err -> error err

However I get the same error with this:

但是我得到了同样的错误:

test: Unable to read String

It's compiled with GHC 7.0.3 and the source was edited with vim. However even string data passed in from outside the app generate the same error. Really out of ideas now...

它是用GHC 7.0.3编译的,源代码是用vim编辑的。但是,即使从应用程序外部传入的字符串数据也会产生相同的错误。现在真的没有想法......

2 个解决方案

#1


3  

Use print instead of putStrLn, which only works on Strings:

使用print而不是putStrLn,它只适用于字符串:

import qualified Text.JSON as JS

main :: IO ()
main = do
   case JS.decode "{}" of
            JS.Ok value -> print (value :: JSValue)
            JS.Error err -> error err

#2


2  

I think this is just a capitalization issue with JS.Decode instead of JS.decode. The following works fine for me with the latest Haskell platform.

我认为这只是JS.Decode而不是JS.decode的大写问题。使用最新的Haskell平台,以下工作正常。

module Foo where
import qualified Text.JSON as JS

foo :: IO ()
foo = case JS.decode "{}" of
   JS.Ok value -> putStrLn value
   JS.Error err -> error err

#1


3  

Use print instead of putStrLn, which only works on Strings:

使用print而不是putStrLn,它只适用于字符串:

import qualified Text.JSON as JS

main :: IO ()
main = do
   case JS.decode "{}" of
            JS.Ok value -> print (value :: JSValue)
            JS.Error err -> error err

#2


2  

I think this is just a capitalization issue with JS.Decode instead of JS.decode. The following works fine for me with the latest Haskell platform.

我认为这只是JS.Decode而不是JS.decode的大写问题。使用最新的Haskell平台,以下工作正常。

module Foo where
import qualified Text.JSON as JS

foo :: IO ()
foo = case JS.decode "{}" of
   JS.Ok value -> putStrLn value
   JS.Error err -> error err