2

Decoding JSON lists using Mochijson produces erroneous results depending on the list values.

For example:

Eshell V5.9.1  (abort with ^G)
1> c(mochijson).
{ok,mochijson}
2> mochijson:decode("[]").
{array,[]}
3> mochijson:decode("[100]").
{array,"d"}
4> mochijson:decode("[100,100]").
{array,"dd"}
5> mochijson:decode("[20,20]").       
{array,[20,20]}
6> mochijson:decode("[30,30]").
{array,[30,30]}
7> mochijson:decode("[35,35]").
{array,"##"}
8> mochijson:decode("[\"Hello\",35]").
{array,["Hello",35]}

My problem is that lines 3,4 and 7 are converting the list items into their ascii equivalents not decoding them as integers.

Any pointers either to an different JSON library or workaround/fix appreciated. :-)

2 Answers2

1

They are being translated to numbers, it's just that erlang shell whenever is showing a list of integers it will show them as ASCII representatives on the shell. but they are valid numbers. if you print them out with io:format("~w") you will see the numbers, and also in your code you can treat them as integers.

Khashayar
  • 2,014
  • 3
  • 22
  • 31
1

To clarify @Khashayar's comment, Erlang strings are lists of integers. The shell basically has to guess whether to display it like a string or a list of integers, based on the values of those integers. There is no tag to say that it is a string. You can prove this to yourself very easily in the shell.

1> [].
[]
2> [100].
"d"

mochijson2 makes this a bit more straightforward by using the binary type to represent strings. I highly recommend using this library instead of mochijson, it is far more popular.

1> mochijson2:decode("[]").
[]
2> mochijson2:decode("[100]").
"d"
3> mochijson2:decode("[\"hello\"]").
[<<"hello">>]