Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Creating JSON object from 2 collections

I'm using Postgrex in Elixir, and when it returns query results, it returns them in the following struct format:

%{columns: ["id", "email", "name"], command: :select, num_rows: 2, rows: [{1, "[email protected]", "Bobbly Long"}, {6, "[email protected]", "Woll Smoth"}]}

It should be noted I am using Postgrex directly WITHOUT Ecto.

The columns (table headers) are returned as a collection, but the results (rows) are returned as a list of tuples. (which seems odd, as they could get very large).

I'm trying to find the best way to programmatically create JSON objects for each result in which the JSON key is the column title and the JSON value the corresponding value from the tuple.

I've tried creating maps from both, merging and then serialising to JSON objects but it seems there should be an easier/better way of doing this.

Has anyone dealt with this before? What is the best way of creating a JSON object from a separate collection and tuple?

like image 562
Robin Johnson Avatar asked Jul 05 '15 23:07

Robin Johnson


1 Answers

Something like this should work:

result = Postgrex.query!(...)

Enum.map(result.rows, fn row ->
  Enum.zip(result.columns, Tuple.to_list(row))
  |> Enum.into(%{})
  |> JSON.encode
end)

This will result in a list of json objects where each row in the resultset is a json object.

like image 104
Eric Meadows-Jönsson Avatar answered Sep 21 '22 01:09

Eric Meadows-Jönsson