基本上,你得到的是 json 编码的数据,所以首先你需要对其进行解码,然后实现一些过滤/查找机制。我的方法是使用jiffy json parser:
首先,克隆并构建 jiffy:
git clone git@github.com:davisp/jiffy.git;
cd jiffy; make
在运行 erlang 命令行客户端时,您必须将 jiffy 添加到代码路径:
erl -pa Private/jiffy/ebin -pa Private/jiffy/deps
最后,根据姓名获取年龄的实现:
-module(test).
-compile(export_all).
decode(Results) ->
[jiffy:decode(E)||E<-Results].
get_age(_, []) ->
erlang:throw(name_not_found);
get_age(Name, [{H}|T]) ->
case proplists:get_value(<<"name">>, H) of
Name -> proplists:get_value(<<"age">>, H);
_ -> get_age(Name, T)
end.
用法:
erl -pa Private/jiffy/ebin -pa Private/jiffy/deps
Erlang R16B03 (erts-5.10.4) [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V5.10.4 (abort with ^G)
1> application:start(jiffy).
ok
2> c(test).
{ok,test}
3> {ok, [{0, Results}]} = {ok,[{0,
3> [<<"{\"age\": 24, \"name\": \"krishna\"}">>,
3> <<"{\"age\": 29, \"name\": \"sharat\"}">>,
3> <<"{\"age\": 25, \"name\": \"ramesh\"}">>,
3> <<"{\"age\": 28, \"name\": \"kumar\"}">>,
3> <<"{\"age\": 24, \"name\": \"gopi\"}">>,
3> <<"{\"age\": 27, \"name\": \"anil\"}">>]}]}.
{ok,[{0,
[<<"{\"age\": 24, \"name\": \"krishna\"}">>,
<<"{\"age\": 29, \"name\": \"sharat\"}">>,
<<"{\"age\": 25, \"name\": \"ramesh\"}">>,
<<"{\"age\": 28, \"name\": \"kumar\"}">>,
<<"{\"age\": 24, \"name\": \"gopi\"}">>,
<<"{\"age\": 27, \"name\": \"anil\"}">>]}]}
4> Decoded = test:decode(Results).
[{[{<<"age">>,24},{<<"name">>,<<"krishna">>}]},
{[{<<"age">>,29},{<<"name">>,<<"sharat">>}]},
{[{<<"age">>,25},{<<"name">>,<<"ramesh">>}]},
{[{<<"age">>,28},{<<"name">>,<<"kumar">>}]},
{[{<<"age">>,24},{<<"name">>,<<"gopi">>}]},
{[{<<"age">>,27},{<<"name">>,<<"anil">>}]}]
5> test:get_age(<<"krishna">>, Decoded).
24
6>