Skip to content

Instantly share code, notes, and snippets.

@sile
Created February 14, 2017 11:43
Show Gist options
  • Save sile/f06762470a46f50081ee7d01ee8d91e3 to your computer and use it in GitHub Desktop.
Save sile/f06762470a46f50081ee7d01ee8d91e3 to your computer and use it in GitHub Desktop.
jsoneのデコード失敗時にエラー行番号を取得する
-module(json_error_line).
-export([parse_json/1]).
-spec parse_json(binary()) -> {ok, term()} | {error, Line::integer(), term()}.
parse_json(Json) ->
case jsone:try_decode(Json) of
{ok, Value, _} ->
{ok, Value};
{error, {badarg, [{_, _, [Rest | _], _} | _]} = Reason} ->
ConsumedSize = byte_size(Json) - byte_size(Rest),
<<Bin:ConsumedSize/binary, _/binary>> = Json,
Line = length(binary:split(Bin, <<"\n">>)),
{error, Line, Reason};
{error, Reason} ->
{error, -1, Reason}
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment