Skip to content

Instantly share code, notes, and snippets.

@fuCtor
Last active May 25, 2016
Embed
What would you like to do?
JSON multi object stream parsing with Elixir
defmodule Chunk do
def parse(text) do
case :jsx.decoder(Chunk, [], [:return_tail]).(text) do
{:with_tail, item, ""} -> {item, nil}
{:with_tail, item, tail} -> {item, fn() -> parse(tail) end }
other -> other
end
end
def init(_) do
fn(v) -> v end
end
def handle_event(:end_json, state),
do: state
def handle_event(:start_object, state),
do: {%{}, state }
def handle_event(:start_array, state),
do: {[], state }
# end_object end_array
def handle_event(event, {object, merge_func}) when is_function(merge_func) and is_atom(event),
do: merge_func.(object)
def handle_event({:key, key}, {object, merge_func}) when is_map(object),
do: fn(value) -> {Map.put(object, key, value), merge_func} end
def handle_event({_, value}, merge_func) when is_function(merge_func),
do: merge_func.(value)
def handle_event(:end_object, {object, {array, merge_func}}),
do: {array ++ [object], merge_func}
def handle_event({_, value}, {array, merge_func}) when is_list(array),
do: { array ++ [value], merge_func }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment