Erlang:元组列表到JSON [英] Erlang : Tuple List into JSON

查看:307
本文介绍了Erlang:元组列表到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表,它们是http头。我想将列表转换为JSON对象。我尝试mochijson2但没有用。

I have a list of tuples which are http headers. I want to convert the list to a JSON object. I try mochijson2 but to no avail.

所以我有以下:

[{'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字符串):

And would like this ( a binary JSON string ) :

<<"{\"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是元组的原始列表:

And I try this where A is the original list of tuples :

list_to_binary(mochijson2:encode(A)).

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

I suspect I need to get it into a format that mochijson2 can interpret better. 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.

推荐答案

您需要将这些字符串转换为之前的二进制,将其发送到编码器。 mochijson2编码器将其视为整数列表,并将其作为数组输出。因此,mochijson2需要您将 {'key',val} 转换为 {'key',<val>> ;}

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. So mochijson2 needs you to convert{'key', "val"} into {'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]).

或者您喜欢使用乐趣:

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

这篇关于Erlang:元组列表到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆