How to return a structured JSON with column names and values in Mariaex

I am using Mariaex without Ecto to query a MySQL database for one of my projects, I get results like this:

%Mariaex.Result{
  columns: ["type", "voucher", "item_code", "sum"],
  connection_id: #PID<0.1220.0>,
  last_insert_id: nil,
  num_rows: 14,
  rows: [
    [11, "000036", "0004", 40.0],
    [11, "000180", "0011", 10.0],
    [11, "000038", "0041", 5.0],
    [11, "000180", "0042", 5.0],
    [11, "000037", "0048", 65.0],
    [11, "000036", "0074", 5.0],
    [11, "000036", "0081", 10.0],
    [11, "000036", "0083", 16.0],
    [11, "000038", "0087", 5.0],
    [11, "000038", "0089", 5.0],
    [11, "000036", "0092", 10.0],
    [11, "000035", "0093", 15.0],
    [11, "000037", "0097", 37.0],
    [11, "000243", "0100", 6.0]
  ]
}

How to return this data as JSON like this:

{
"type": 11,
"voucher": "000036",
..
},
{
"type": 11,
"voucher": "000180",
..
}

Thank you.

You can transform it yourself, probably. According to your examples, it would be something like

@spec to_maps(Mariaex.Result.t()) :: [map()]
def to_maps(%Mariaex.Result{columns: columns, rows: rows}) do
  Enum.map(rows, fn row ->
    columns
    |> Enum.zip(row)
    |> Enum.into(%{})
  end)
end

and then you can use any of the json encoders

result # Mariaex.Result.t()
|> to_maps()
|> Jason.encode!()
2 Likes

Thank you very much, that provides the expected result. I admit, I have some learning to do when it comes to lists and maps.