murty
murty

Reputation: 41

ERLANG JSON decode error

I am getting the following error.. when i run "earTest:input("hai","1","0.1")." on erlang shell. could you pls help me out..(any issue with my encode/decode?).

** 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)

Code:

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

Upvotes: 0

Views: 241

Answers (1)

Pascal
Pascal

Reputation: 14042

You are trying to decode the non encoded json, and you have created a nested structure.

replace by

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

Upvotes: 1

Related Questions