2

Let's say I want to use Aeson to parse the following JSON object:

{
    "data": [
        [ 
            "data",
            "more data"
        ],
        [ 
            "data",
            "more data"
        ]
    ],
    "error": {
        "code": ""
    }
}

I can create the records for the JSON objects, then create the instances to parse the pieces out like the documentation describes. But, I'm really only interested in the Vector Text that's inside data. Is there a more direct way to get at this than creating the records? It's not obvious how to create the Parser that gets me this directly.

1 Answers1

2

It appears that there is an Aeson tutorial documenting exactly this problem: Parsing without creating extra types

In your case, data has arrays of arrays, so I'm not sure if you want a Vector (Vector Text) or flatten all of it into one array, but adapting from the documentation:

justData :: Value -> Parser (Vector (Vector Text))
justData = withObject "structure with data" $ \o -> o .: "data"

justDataFlat :: Value -> Parser (Vector Text)
justDataFlat value = fmap join (justData value)

Also note that if your structure is deeper, like this:

{
    "data": {
        "deep": [
            "data",
            "more data"
        ]
    }
}

you can use .: more than once:

deeperData :: Value -> Parser (Vector Text)
deeperData = withObject "structure with deeper data" $ \o ->
    step1 <- o .: "data"
    step1 .: "deep"
Koterpillar
  • 7,883
  • 2
  • 25
  • 41
  • Thanks. But, to be sure, that isn't in the Aeson documentation. It is in a separate Aeson tutorial. I did not find this before posting the question. –  Feb 24 '19 at 04:14
  • Sorry, I thought it was - found it by searching for "aeson". – Koterpillar Feb 24 '19 at 04:32