简体   繁体   English

Erlang:元组列表到JSON

[英]Erlang : Tuple List into JSON

I have a list of tuples which are http headers. 我有一个元组列表,它们是http标头。 I want to convert the list to a JSON object. 我想将列表转换为JSON对象。 I try mochijson2 but to no avail. 我尝试mochijson2但无济于事。

So I have the following : 所以我有以下内容:

[{'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"}]

And would like this ( a binary JSON string ) : 并希望这(二进制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\"}">>

And I try this where A is the original list of tuples : 我尝试这个,其中A是元组的原始列表:

list_to_binary(mochijson2:encode(A)).

I suspect I need to get it into a format that mochijson2 can interpret better. 我怀疑我需要把它变成mochijson2可以更好地解释的格式。 And then convert to binary. 然后转换为二进制。 Or figure out a way to have all the characters represented as strings (rather than have some as list of integers). 或者找出一种方法将所有字符表示为字符串(而不是将其作为整数列表)。

Greatly appreciated if you could point me in the right direction with some sample code. 非常感谢,如果你能用一些示例代码指出我正确的方向。

You need to convert those strings inside there into binary before you send it to the encoder. 将其发送到编码器之前,您需要将其中的字符串转换为二进制。 The mochijson2 encoder just considers this as a list of integers and outputs it as an array. mochijson2编码器只将其视为整数列表并将其作为数组输出。 So mochijson2 needs you to convert {'key', "val"} into {'key', <<"val">>} 所以mochijson2需要你将{'key', "val"}转换为{'key', <<"val">>}

Try this in your code: 在您的代码中尝试此操作:

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]).

Or if you prefer using Funs: 或者如果您更喜欢使用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]).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM