Created
October 12, 2022 14:46
-
-
Save kerryb/ad559eca963dd8ae0259e2431d9470d9 to your computer and use it in GitHub Desktop.
Horrible code to convert some nested text data to json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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