简体   繁体   English

如何使用Aeson解析整数

[英]How do I parse an Integer with Aeson

I'm using the highly recommended Aeson package, but I need to parse integers. 我正在使用强烈推荐的Aeson软件包,但是我需要解析整数。 I'd like to do something like: 我想做类似的事情:

decode "5" :: Maybe Int

and grab the result, but as the documentation explains ( http://hackage.haskell.org/package/aeson-0.8.0.0/docs/Data-Aeson.html ), Aeson does not support parsing simple types (brilliant idea!): 并获取结果,但是正如文档说明( http://hackage.haskell.org/package/aeson-0.8.0.0/docs/Data-Aeson.html )所示,Aeson不支持解析简单类型(精妙的主意!) :

>>> decode (encode (1 :: Int)) :: Maybe Int
Nothing

You're referenced to use the value parser rather than the json parser, but there's no indication of how to actually use that parser. 引用您使用值解析器而不是json解析器,但是没有指示如何实际使用该解析器。 If you look at the source for decode, you see that internally Aeson has a decodeWith option that takes a parser, but that's hidden from you. 如果您查看解码源,您会发现Aeson在内部具有带解析器的encodeWith选项,但是对您而言是隐藏的。 It seems like importing Data.Attoparsec and running parse value "5" might work, but I've had trouble getting meaningful results from that as well. 似乎导入Data.Attoparsec并运行parse value "5"可能有效,但是我也很难从中获取有意义的结果。

This won't work because JSON doesn't support 1 as a valid JSON document, the only top-level values that are valid JSON are objects and arrays. 这将不起作用,因为JSON不支持1作为有效JSON文档,而有效JSON的唯一顶级值是对象和数组。 You can easily fix this by putting square brackets around the value and decoding it as a list of Int s: 您可以通过在值周围放置方括号并将其解码为Int列表来轻松解决此问题:

> decode "[1]" :: Maybe [Int]
Just [1]

The decode function only converts JSON documents to Haskell values, not just JSON values to Haskell values. decode功能仅将JSON文档转换为Haskell值,而不仅仅是JSON值转换为Haskell值。 You can see this in the docs under json : 您可以在json下的文档中看到此内容:

Parse a top-level JSON value. 解析顶级JSON值。 This must be either an object or an array, per RFC 4627. 根据RFC 4627,它必须是对象或数组。

However, to actually use the value parser using Data.Attoparsec and Data.Aeson.Parser : 但是,要通过Data.AttoparsecData.Aeson.Parser实际使用value解析器:

> parseOnly value "1"
Right (Number 1.0)

And via simple pattern matches you can extract that value to a Data.Scientific.Scientific value, which Aeson uses as it's numeric type. 通过简单的模式匹配,您可以将该值提取到Data.Scientific.Scientific值,Aeson将其用作数字类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM