Elixir - Creating a JSON Object from 2 Collections

I use Postgrex in Elixir, and when it returns the query results, it returns them in the following structure format:

%{columns: ["id", "email", "name"], command: :select, num_rows: 2, rows: [{1, " me@me.com ", "Bobbly Long"}, {6, " email@tts.me ", "Woll Smoth"}]} 

It should be noted that I use Postgrex directly WITHOUT Ecto.

Columns (table headers) are returned as a collection, but results (rows) are returned as a list of tuples. (which seems strange as they can get very large). A.

I am trying to find a better way to programmatically create JSON objects for each result, in which the JSON key is the column heading and the JSON value is the corresponding value from the tuple.

I tried creating cards from both, merging, and then serializing with JSON objects, but it seems like this should be simpler / better.

Has anyone dealt with this? What is the best way to create a JSON object from a separate collection and tuple?

+5
source share
1 answer

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 result set is a json object.

+7
source

All Articles