0
\$\begingroup\$

I wrote this module that converts json to a nested structure based on its parent id.

Takes this json input:

{
  "0": [
    {
      "id": 1,
      "title": "Foo",
      "children": [],
      "parent_id": null
    }
  ],
  "1": [
    {
      "id": 2,
      "title": "Bar",
      "children": [],
      "parent_id": 1
    },
    {
      "id": 2,
      "title": "Baz",
      "children": [],
      "parent_id": 1
    }
}

And converts it like this:

[
    {
        "id": 10,
        "level": 0,
        "parent_id": null,
        "title": "Foo",
        "children": [ // Bar & Baz go here ]
    }
]

This is what I came up with. It recursively does the conversion. Looking for any improvements. Particularly in terms of optimization.

defmodule JSONConverter do

  def action(body) do
    body
      |> flatten
      |> convert([], nil)
  end

  defp flatten(content) do
    Enum.reduce(content, [], fn {_, maps}, acc -> acc ++ maps end)
  end

  defp convert(source, target, n) do
    data = Enum.filter(source, fn val -> val["parent_id"] == n end)
    if length(data) > 0 do
      target ++ Enum.map(data, fn(x) ->
        Map.put(x, "children", convert(source, [], x["id"]))
      end)
    else
      target
    end
  end

end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.