alinbsp/erlcourse2

Implement a json to erlang data structure function

Opened this issue · 2 comments

Implement a json to erlang data structure function

printrecrec(#accountDetails{name=Name, balance=Balance, pin=Pin}) ->
"name= " ++ Name ++ ",\nbalance= " ++ integer_to_list(Balance) ++ ",\npin= " ++ integer_to_list(Pin) ++ "\n}".

printrec(#account{id=Id, details=Details}) ->
"account{\nid= " ++ integer_to_list(Id) ++ ",\n" ++ printrecrec(Details).

json_to_record({struct, Json}) ->
NewList = lists:map(fun({K, V}) when K =:= <<"name">> -> {binary_to_list(K), binary_to_list(V)};
({K, V}) -> {binary_to_list(K), V}
end, Json),
Id = proplists:get_value("id", NewList, -1),
Name = proplists:get_value("name", NewList, ""),
Balance = proplists:get_value("balance", NewList, "wd"),
Pin = proplists:get_value("pin", NewList, -1),
Acc=#account{id = Id, details=#accountDetails{name = Name, balance = Balance, pin = Pin}}.

loop() {
..
"create_json" ->
Body = Req:recv_body(),
Json = mochijson2:decode(Body), %%RETURNS A TUPLE
Recordul = json_to_record(Json),
Req:respond({200, [{"Content-Type", "text/plain"}], printrec(Recordul)});
}