[Haskell-beginners] help understanding JSON

Yitzchak Gale gale at sefer.org
Tue May 10 11:32:10 CEST 2011


Sean Perry wrote:
> I have some JSON which looks like this:
> {"count":2, "result":[{"LastTrade":"31.24", "Symbol":"FOO"},
>                                  {"LastTrade":"345.12", "Symbol":"BAR"}]}
> ...Is there some way to convince the JSON text parser to turn "12.34"
> into (Double 12.34)??

No, and rightly so. It is encoded as a string in the JSON itself,
so that is the way the library should parse it. If you need to interpret
certain strings in the JSON as encoded numbers, that is a
separate step in your program logic and should be represented
that way.

People using languages that blur the lines between numbers
and their string representation are often sloppy about
their JSON design in this way.

If you want, you can easily write a function

sloppyJson :: Value -> Value

which replaces string representations of numbers by numbers
wherever possible. It might be useful sometimes. But
not always - it certainly happens that certain fields happen
to contain something that looks like a number but actually
must remain a string. Usually the best practice is to
convert the JSON Value to your own type-safe representation
of the data, wrapping the result in Maybe (or a richer error
type) to handle cases where the conversion from string fails.

> Mostly this boils down to a complete lack of useful docs.
> A laundry list of functions is not always helpful.

Actually, it often is helpful in Haskell, because the
type signatures of the functions are very eloquent. Here,
the "json" function produces a value of type Parser Value.
Clicking on "Parser" will get you complete instructions
on how to use those (in this case it happens to be a
Parser from the attoparsec package, which you will
see immediately), and clicking on "Value" will
get you complete instructions on how to use those
once you have obtained them by parsing.

Of course, you are right that it would be much better
if the documentation would include at least a few
words that give you a basic idea even before you
click. But since all the information is actually there
and easy to obtain in a standard way, you can
understand why Haskell coders are often a bit too
lazy about that.

Regards,
Yitz



More information about the Beginners mailing list