Module jsonpull_construct

These functions are helpers to construct a proper Erlang list or map from JSON equivalents.

Description

These functions are helpers to construct a proper Erlang list or map from JSON equivalents.

They can be used with the main functions that return {ok, {Value, Rest}} or {error, Atom} and also have the same signature themselves.

However, you can also substitute your own function to construct whatever you'd like.

Function Index

list/2Tries to read an array from the JSON and constructs a list using Fun.
map/2Equivalent to jsonpull_construct:fold(JSON, #{}, Conditions).
fold/3Tries to read an object from the JSON and constructs a value using Conditions.

Function Details

list/2

list(JSON::binary(), Fun) -> {ok, {List, Rest::binary()}} | {error, Error | not_array}

Tries to read an array from the JSON and constructs a list using Fun.

The Fun should have the same signature as one of the main reading functions. You can also use an atom as a shorthand for the main functions, e.g. 'string' instead of 'fun jsonpull:string/1'.

map/2

map(JSON::binary(), Conditions) -> {ok, {Map, Rest::binary()}} | {error, Error | not_object | failed_condition}

Equivalent to jsonpull_construct:fold(JSON, #{}, Conditions).

fold/3

fold(JSON::binary(), Acc0, Conditions) -> {ok, {Acc1, Rest::binary()}} | {error, Error | not_object | failed_condition}

Tries to read an object from the JSON and constructs a value using Conditions.

The conditions can be seen as a list of items to check. Each condition will only apply once. It works like this:
  1. A new key is pulled from the object
  2. The key is checked to find any condition that matches it. If no condition is found, the value is skipped.
  3. When a key has a matching condition, the Fun for that condition is called to read the value.
  4. If it's a required condition, the constructor will make sure it only gets called once by erroring out if the condition matches any key again.
  5. If it's an optional condition, the constructor will make sure it only gets called once by silently ignoring any further mathces.
  6. When the object runs out of keys, if there are any required conditions left, an error will be returned.

A single condition can have any number of Key-Fun pairs. Each pair contains the Key to check, and the Fun to be called if found.

The Fun receives the JSON to read and the current accumulator. You may modify the accumulator in any way you'd like. There are some shortcut tuples you can use instead of supplying a Fun yourself, such as
 {set, name, string} % the third element can be a main-ish fun or an atom that refers to one
 
instead of
 fun (Bin, Acc) ->
     {ok, {Name, Rest}} = jsonpull:string(Bin),
     {ok, {Acc#{name => Name}, Rest}}
 end
 
{set, Key, ...} will behave differently depending on the type of your accumulator. This is still pretty complicated. Please look at some of the examples if you need more info.


Generated by EDoc