简体   繁体   English

在Erlang中使用Jiffy将JSON属性名称解码为列出字符串而不是二进制字符串

[英]Decode JSON property names to list strings instead of binary strings using Jiffy in Erlang

I have a tuple generated using jiffy library. 我有一个使用jiffy库生成的元组。

For example : jiffy:decode(<<"{\\"foo\\":\\"bar\\"}">>). 例如: jiffy:decode(<<"{\\"foo\\":\\"bar\\"}">>). results in 结果是
{[{<<"foo">>,<<"bar">>}]}

I want <<"foo">> to be "foo" 我希望<<"foo">>成为"foo"

Is there a way for converting the <<"foo">> to "foo" ? 有没有办法将<<"foo">>转换为"foo"

Basically I want to convert this: 基本上我想转换这个:

[{<<"t">>,<<"getWebPagePreview">>},{<<"message">>,<<"google.com">>}]

into this: 进入这个:

[{"t",<<"getWebPagePreview">>},{"message",<<"google.com">>}]

note: consider this to be a very large list, and I want an efficient solution. 注意:认为这是一个非常大的列表,我想要一个有效的解决方案。

there is a function to transform a binary <<"hello">> into a list "hello" : 有一个函数将二进制<<"hello">>转换为列表"hello"

1> binary_to_list(<<"hello">>).
"hello"
2> L = [{<<"t">>,<<"getWebPagePreview">>},{<<"message">>,<<"google.com">>}].
[{<<"t">>,<<"getWebPagePreview">>},
 {<<"message">>,<<"google.com">>}]

You can apply this to your list using a list comprehension: 您可以使用列表推导将其应用于列表:

3> [{binary_to_list(X),Y} || {X,Y} <- L].
[{"t",<<"getWebPagePreview">>},{"message",<<"google.com">>}]
4>

you can embed this in a function: 你可以将它嵌入到一个函数中:

convert(List) ->
    F = fun({X,Y}) -> {binary_to_list(X),Y} end,
    [F(Tuple) || Tuple <- List].

Because (when) order of elements doesn't matter the most efficient version is 因为(当)元素的顺序无关紧要,最有效的版本是

convert({List}) ->
    {convert(List, [])}.

convert([], Acc) -> Acc;
convert([{X, Y}|T], Acc) ->
    convert(T, [{binary_to_list(X), Y}|Acc]).

When you want to preserve order of element strightforward version with list comprehension 当你想用list rerehension保存元素strightforward版本的顺序时

convert({List}) ->
    {[{binary_to_list(X), Y} || {X, Y} <- List]}.

is the (almost) exact equivalent of 是(几乎)精确等价的

convert({List}) ->
    {convert_(List)}.

convert_([]) -> [];
convert_([{X, Y}|T]) ->
    [{binary_to_list(X), Y}|convert_(T)].

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

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