mochijson2 or mochijson

我只是一个虾纸丫 提交于 2019-12-05 23:03:45

问题


I'm encoding some data using mochijson2. But I found that it behaves strange on strings as lists.

Example:

mochijson2:encode("foo").

[91,"102",44,"111",44,"111",93]

Where "102", "111", "111" are $f, $o, $o encoded as strings 44 are commas and 91 and 93 are square brakets.

Of course if I output this somewhere I'll get string "[102,111,111]" which is obviously not that what I what.

If i try

mochijson2:encode(<<"foo">>).

[34,<<"foo">>,34]

So I again i get a list of two doublequotes and binary part within which can be translated to binary with list_to_binary/1

Here is the question - why is it so inconsistent. I understand that there is a problem distingushing erlang list that should be encoded as json array and erlang string which should be encoded as json string, but at least can it output binary when i pass it binary?

And the second question: Looks like mochijson outputs everything nice (cause it uses special tuple to designate arrays {array, ...})

mochijson:encode(<<"foo">>).
"\"foo\""

What's the difference between mochijson2 and mochijson? Performance? Unicode handling? Anything else?

Thanks


回答1:


My guess is that the decision in mochijson is that it treats a binary as a string, and it treats a list of integers as a list of integers. (Un?)fortunately strings in Erlang are in fact a list of integers.

As a result your "foo", or in other words, your [102,111,111] is translated into text representing "[102,111,111]". In the second case your <<"foo">> string becomes "foo"

Regarding the second question, mochijson seems to always return a string, whereas mochijson2 returns an iodata type. Iodata is basically a recursive list of strings, binaries and iodatas (in fact iolists). If you only intend to send the result "through the wire", it is more efficient to just nest them in a list than convert them to a flat string.



来源:https://stackoverflow.com/questions/1562235/mochijson2-or-mochijson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!