Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Merge pull request #5 from jeremey/add_json_arrays

Add support for JSON arrays as lists of Erlson dictionaries
  • Loading branch information...
commit cae2a1e987bf6c96b8bff8693d2c15d154198164 2 parents 1aca8bf + e32e7a6
Anton Lavrik authored

Showing 1 changed file with 32 additions and 0 deletions. Show diff stats Hide diff stats

  1. +32 0 src/erlson.erl
32 src/erlson.erl
@@ -29,6 +29,7 @@
29 29 % public API
30 30 -export([from_proplist/1, from_nested_proplist/1, from_nested_proplist/2]).
31 31 -export([to_json/1, from_json/1]).
  32 +-export([list_to_json_array/1, list_from_json_array/1]).
32 33 % these two functions are useful, if there's a need to call mochijson2:decode
33 34 % and mochijson2:encode separately
34 35 -export([to_json_term/1, from_json_term/1]).
@@ -225,6 +226,23 @@ to_json_term(Dict) ->
225 226 end.
226 227
227 228
  229 +% @doc Convert a list of Erlson dictionaries to a JSON array
  230 +-spec list_to_json_array/1 :: (List :: [orddict()]) -> iolist().
  231 +list_to_json_array(List) ->
  232 + JsonStruct = list_to_json_term(List),
  233 + mochijson2:encode(JsonStruct).
  234 +
  235 +
  236 +% @doc Convert list of Erlson dictionaries to list of JSON abstract terms
  237 +list_to_json_term(List) ->
  238 + try [encode_json_term(X) || X <- List]
  239 + catch
  240 + 'erlson_bad_json' ->
  241 + erlang:error('erlson_bad_json', [List])
  242 + end.
  243 +
  244 +
  245 +
228 246 to_json_struct(Dict) when is_list(Dict) ->
229 247 Fields = lists:map(fun to_json_field/1, Dict),
230 248 {'struct', Fields};
@@ -273,6 +291,20 @@ from_json_term(JsonTerm) ->
273 291 erlang:error('erlson_json_struct_expected', [JsonTerm]).
274 292
275 293
  294 +% @doc Create list of Erlson dictionaries from JSON array
  295 +-spec list_from_json_array/1 :: (Json :: iolist()) -> [orddict()].
  296 +list_from_json_array(Json) ->%, list_to_json_array, list_from_json_term and list_to_json_term
  297 + JsonTerm = mochijson2:decode(Json),
  298 + list_from_json_term(JsonTerm).
  299 +
  300 +
  301 +% @doc Create list of Erlson dictionaries from list of JSON abstract terms
  302 +list_from_json_term(JsonTerm) when is_list(JsonTerm) ->
  303 + decode_json_term(JsonTerm);
  304 +list_from_json_term(JsonTerm) ->
  305 + erlang:error('erlson_json_array_expected', [JsonTerm]).
  306 +
  307 +
276 308 decode_json_term(X) when
277 309 is_binary(X); % JSON string
278 310 is_integer(X); is_float(X); % JSON number

0 comments on commit cae2a1e

Please sign in to comment.
Something went wrong with that request. Please try again.