使用aeson的形式键 - 值对的值
我很难以形式解析JSON文本,
{
"Person1": {
"name": "John Doe",
"job" : "Accountant",
"id": 123
},
"Person2": {
"name": "Jane Doe",
"job" : "Secretary",
"id": 321
}}
如下所示,我定义了新的数据类型
data Person = Person
{ name :: String
, job :: String
, id :: Int } deriving Show
,但是在这种情况下,在定义fromjson
的实例上遇到了麻烦。
现在,如果JSON文本是
{
"People": [
{
"name": "John Doe",
"job": "Accountant",
"id": 123
},
{
"name": "Jane Doe",
"job": "Secretary",
"id": 321
}]
}
我可以写
instance FromJSON person where
parseJSON = withObject "Person" $ \obj -> Person
<$> obj .: "name"
<*> obj .: "job"
<*> obj .: "id"
的,但我不知道如何将此模式转换为其他格式。
I'm having trouble parsing JSON text in the form
{
"Person1": {
"name": "John Doe",
"job" : "Accountant",
"id": 123
},
"Person2": {
"name": "Jane Doe",
"job" : "Secretary",
"id": 321
}}
I define a new data type as follows
data Person = Person
{ name :: String
, job :: String
, id :: Int } deriving Show
But am having trouble defining an instance of FromJSON
in this case.
Now if the JSON text were in the form of
{
"People": [
{
"name": "John Doe",
"job": "Accountant",
"id": 123
},
{
"name": "Jane Doe",
"job": "Secretary",
"id": 321
}]
}
I could write
instance FromJSON person where
parseJSON = withObject "Person" $ \obj -> Person
<gt; obj .: "name"
<*> obj .: "job"
<*> obj .: "id"
But I don't know how to translate this pattern to the other format.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON字典,例如
{“ foo”:“ bar”}
可以将其解码为诸如map
从“容器”软件包或hashmap
中解码。来自无序的容器。一旦您拥有fromjson实例的人,只需使用aeson.decode
获取MAP TEXT PERTENS
。如果您想获得[Person]
,则可以进一步使用data.map.elems
。例如:
有趣的一点是
aeson.decode
正在返回类型map String Person
。一切都在那里进行完整的演示。您可以使用输入进行测试:
要查看以下输出:
如果要删除
person1
和Person2
标签,则只需使用data获取地图的元素.map.elems
。A JSON dictionary, such as
{ "foo" : "bar" }
can be decoded into Maps such asMap
from the containers package orHashMap
from unordered-containers. Once you have your FromJSON instance for Person then just useAeson.decode
to get aMap Text Person
. If you'd like to get[Person]
then you could further useData.Map.elems
.For example:
The interesting bit is that
Aeson.decode
is returning a typeMap String Person
. Everything is is just there to make a complete demonstration.You can test this with the input:
To see output of:
If you want to drop the
Person1
andPerson2
tags then just get the elements of the Map usingData.Map.elems
.