Erlang : Tuple List into JSON

前端 未结 1 2081
执笔经年
执笔经年 2021-02-15 16:15

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.

So I have the following :



        
相关标签:
1条回答
  • 2021-02-15 17:18

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

    Or if you prefer using 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]).
    
    0 讨论(0)
提交回复
热议问题