Skip to content

Instantly share code, notes, and snippets.

@kerryb
Created October 12, 2022 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerryb/ad559eca963dd8ae0259e2431d9470d9 to your computer and use it in GitHub Desktop.
Save kerryb/ad559eca963dd8ae0259e2431d9470d9 to your computer and use it in GitHub Desktop.
Horrible code to convert some nested text data to json
text
|> String.split("\n")
|> Enum.reduce({["{"], " "}, fn line, {output, current_indent} ->
case Regex.run(~r/^( +)(.*): ?(.*)/, line, capture: :all_but_first) do
[indent, key, ""] ->
close_braces =
if indent < current_indent do
Enum.map_join(
(String.length(current_indent) - 4)..String.length(indent)//-4,
"",
&"#{String.duplicate(" ", &1)}},\n"
)
else
""
end
{[~s(#{close_braces}#{indent}"#{key}": {) | output], indent}
[indent, key, value] ->
{[~s(#{indent}"#{key}": "#{value}",) | output], indent}
_ ->
{output, current_indent}
end
end)
|> then(fn {output, current_indent} ->
[Enum.map_join(
(String.length(current_indent) - 4)..0//-4,
"",
&"#{String.duplicate(" ", &1)}}\n"
)|output]
end)
|> Enum.reverse()
|> Enum.join("\n")
|> String.replace(~r/,(\s.*\})/, "\\1")
|> Jason.decode!(objects: :ordered_objects)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment