Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy/psycopg2 desreializes my jsons as dicts but doesn't preserve order

I have a psql query that returns a json object. I fetch this query with results.fetchall() and I get the json properly as a dict. however, as I'm in python 3.4, not yet in 3.6, the objects' order is not preserved in the dict. I saw there's a way to use OrderedDict to keep the order of the json but I'm not sure how to tell sqlalchemy/psycopg2 to use it.

can anybody help please?

like image 538
akiva Avatar asked Aug 06 '17 10:08

akiva


1 Answers

As indicated in the documentation, you must provide a custom deserializer when creating your engine:

from functools import partial
import json, collections

engine = create_engine(
    ...,
    json_deserializer=partial(
        json.loads, 
        object_pairs_hook=collections.OrderedDict),
    )
like image 136
donkopotamus Avatar answered Sep 19 '22 00:09

donkopotamus