6
votes

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?

1
Apparently Postgres can render JSON for you directly, if you should run into performance problems: hashrocket.com/blog/posts/…Patrick Oscity

1 Answers

8
votes

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.