Erlang:元组列表到JSON

时间:2010-10-13 12:06:35

标签: json erlang tuples mochiweb mochijson2

我有一个元组列表,它们是http标头。我想将列表转换为JSON对象。我尝试mochijson2,但无济于事。

所以我有以下内容:

[{'Accept',"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
 {'Accept-Charset',"ISO-8859-1,utf-8;q=0.7,*;q=0.7"},
 {'Accept-Encoding',"gzip,deflate"},
 {'Accept-Language',"en-us,en;q=0.5"},
 {'Cache-Control',"max-age=0"},
 {'Connection',"close"},
 {'Cookie',"uid=CsDbk0y1bKEzLAOzAwZUAg=="},
 {'User-Agent',"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10"}]

并希望这(二进制JSON字符串):

<<"{\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",
 \"Accept-Charset\":\"ISO-8859-1,utf-8;q=0.7,*;q=0.7\",
 \"Accept-Encoding\":\"gzip,deflate\",
 \"Accept-Language\":\"en-us,en;q=0.5\",
 \"Cache-Control\":\"max-age=0\",
 \"Connection\":\"close\",
 \"Cookie\":\"uid=CsDbk0y1bKEzLAOzAwZUAg==\",
 \"User-Agent\":\"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10\"}">>

我尝试这个,其中A是元组的原始列表:

list_to_binary(mochijson2:encode(A)).

我怀疑我需要把它变成mochijson2可以更好地解释的格式。然后转换为二进制。或者找出一种方法将所有字符表示为字符串(而不是将其作为整数列表)。

非常感谢你能用一些示例代码指出我正确的方向。

2 个答案:

答案 0 :(得分:7)

您需要将其中的字符串转换为二进制,然后再将发送给编码器。 mochijson2编码器只将其视为整数列表并将其作为数组输出。因此,mochijson2需要您将{'key', "val"}转换为{'key', <<"val">>}

在您的代码中尝试此操作:

Original = [
  {'Accept-Charset',"ISO-8859-1,utf-8;q=0.7,*;q=0.7"}, 
  {'Accept-Encoding',"gzip,deflate"}
].
StingConverted = [ {X,list_to_binary(Y)} || {X,Y} <- Original ].
Output = mochijson2:encode(StingConverted).
io:format("This is correct: ~s~n", [Output]).

或者如果您更喜欢使用Funs:

Original = [
  {'Accept-Charset',"ISO-8859-1,utf-8;q=0.7,*;q=0.7"}, 
  {'Accept-Encoding',"gzip,deflate"}
].
ConvertFun = fun({X,Y}) -> {X,list_to_binary(Y)} end.
StingConverted = lists:map(ConvertFun, Original).
Output = mochijson2:encode(StingConverted).
io:format("This is correct: ~s~n", [Output]).

答案 1 :(得分:0)

完美无缺。如何将嵌套的Tuple列表导入json? 我修改了代码并尝试了但是失败了。 这就是我现在拥有的。感谢

Nested Tuples List
------------------
Original = [
  {'Accept-Charset',"ISO-8859-1,utf-8;q=0.7,*;q=0.7"}, 
  {'Accept-Encoding',"gzip,deflate"},
  {'Nested-List', [
    {'Accept-Charset',"ISO-8859-1,utf-8;q=0.7,*;q=0.7"}, 
    {'Accept-Encoding',"gzip,deflate"}
  ]}],

ConvertFun = fun({X,Y}) -> {X, case is_list(Y) of
    true -> 
        Elem = lists:nth(1,Y),
        case is_tuple(Elem) of
            true ->
                demo_json(Y);
            false ->
                list_to_binary(Y)
        end;
    false ->
        Y
 end.
} end,
StingConverted = lists:map(ConvertFun, Original),
Output = mochijson2:encode(StingConverted),
io:format("This is correct: ~s~n", [Output]).