ERLANG JSON解码错误

时间:2016-10-29 18:10:34

标签: json erlang decode

我收到以下错误..当我运行“earTest:input(”hai“,”1“,”0.1“)时。”在erlang shell上。你能帮我解决..(我的编码/解码有什么问题吗?)。

** exception error: no function clause matching xmerl_ucs:expand_utf8_1(
    {obj,[{data,[{obj,[{"name","hai"},
    {"number","1"},
    {"marks","0.1"}]}]}]},
    [],0
) (xmerl_ucs.erl, line 435)

in function  xmerl_ucs:from_utf8/1 (xmerl_ucs.erl, line 183)
in call from rfc4627:unicode_decode/1 (rfc4627.erl, line 323)
in call from rfc4627:decode/1 (rfc4627.erl, line 258)
in call from erlTest:outputJ/1 (erlTest.erl, line 10)

代码:

-module(earTest).
-export([input/3]).
-import(rfc4627,[encode/1, decode/1]).

outputJ(X) ->
    {ok, Json, _} = rfc4627:decode(X),
    Airport = rfc4627:get_field(Json, "name", <<>>),
    Airport.   

input(X,Y,Z) ->
    Data = [{obj,[{"name",X},{"number",Y},{"marks",Z}]}],
    JsonData = {obj, [{data, Data}]},
    rfc4627:encode(JsonData),
    outputJ(JsonData).

1 个答案:

答案 0 :(得分:1)

您正在尝试解码非编码的json,并且您已经创建了一个嵌套结构。

替换为

-module(earTest).
-export([input/3]).
-import(rfc4627,[encode/1, decode/1]).

outputJ(X) ->
    {ok, Json, _} = rfc4627:decode(X),
    [Inner_obj] = rfc4627:get_field(Json, "data", <<>>), % extract the inner object
    Airport = rfc4627:get_field(Inner_obj, "name", <<>>),
    Airport.   

input(X,Y,Z) ->
    % Here you are creating a list of one single object element
    Data = [{obj,[{"name",X},{"number",Y},{"marks",Z}]}],
    % and you put it in a "container" object, in the data field
    JsonData = {obj, [{data, Data}]},
    % you have to reuse the result of encoding in the decode function!
    Res = rfc4627:encode(JsonData),
    outputJ(Res).