aeson icon indicating copy to clipboard operation
aeson copied to clipboard

Dealing with empty object from API service

Open rizary opened this issue 7 years ago • 2 comments

Hi, what is the best to handle when we got name: {} (this is from nodejs backend) response from api service, meanwhile what i want is to assume it is 'name: {first: "", last: ""}` so I can parse it to Person {firstName :: Maybe Text, lastName :: Maybe Text} ?

supposed that I have the following types: https://gist.github.com/Rizary/3b3865a145853cf04df7fad4e348a5c3

I finally use optional but actually that's not what I want, because I can't parsed the name: {} as name: {first: "", last: ""}

rizary avatar May 16 '18 10:05 rizary

Sorry for the late reply!

What I'd probably do here is to have one type for deserialization, Person { first :: Maybe Text, last :: Maybe Text } and then provide a total conversion into another type Person2 { first :: Text, last :: Text }. If you want to be fancier you can have just one type data Person f = Person { first :: f Text, last :: f Text }, parse Person Maybe, and provide a conversion Person Maybe -> Person Identity. I doubt that extra complexity is worthwhile though...

If you want to write the FromJSON instance manually instead I think you can use (.:?) to parse the fields and you'll get a Parser (Maybe Text) that you can fmap into a Parser Text.

Do you think that will work, or did you already solve it?

bergmark avatar Jun 23 '18 14:06 bergmark

Hi @bergmark thanks for your answer. I will try it and get back to you.

rizary avatar Jun 23 '18 15:06 rizary