Current section

Files

Jump to
glee src utils.erl
Raw

src/utils.erl

-module(utils).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/utils.gleam").
-export([glee_extract_value_from_json/3]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/utils.gleam", 5).
?DOC(
" Extract a value from a JSON string\n"
" by specifying the parent and key.\n"
).
-spec glee_extract_value_from_json(binary(), binary(), binary()) -> binary().
glee_extract_value_from_json(Json, Parent, Key) ->
Parent_pattern = <<<<"\""/utf8, Parent/binary>>/binary, "\":{"/utf8>>,
Parent_parts = gleam@string:split(Json, Parent_pattern),
case Parent_parts of
[_, Parent_content | _] ->
Key_pattern = <<<<"\""/utf8, Key/binary>>/binary, "\":"/utf8>>,
Key_parts = gleam@string:split(Parent_content, Key_pattern),
case Key_parts of
[_, Value_part | _] ->
By_comma = gleam@string:split(Value_part, <<","/utf8>>),
By_brace = gleam@string:split(Value_part, <<"}"/utf8>>),
Value_by_comma = case By_comma of
[First | _] ->
First;
_ ->
Value_part
end,
Value_by_brace = case By_brace of
[First@1 | _] ->
First@1;
_ ->
Value_part
end,
Value = case string:length(Value_by_comma) < string:length(
Value_by_brace
) of
true ->
Value_by_comma;
false ->
Value_by_brace
end,
Value@1 = gleam@string:trim(Value),
Value@2 = case gleam_stdlib:string_starts_with(
Value@1,
<<"\""/utf8>>
)
andalso gleam_stdlib:string_ends_with(
Value@1,
<<"\""/utf8>>
) of
true ->
gleam@string:slice(
Value@1,
1,
string:length(Value@1) - 2
);
false ->
Value@1
end,
Value@2;
_ ->
<<"Unknown"/utf8>>
end;
_ ->
<<"Unknown"/utf8>>
end.