python - Inconsistent results when exporting JSON from Postgres using Django -
python - Inconsistent results when exporting JSON from Postgres using Django -
i'm trying create django view returns json info postgres (i.e. info postgres of json type).
i utilize django dev server , postgres in development environment, , utilize apache , postgres (a different server) in production environment.
this view works fine in development environment:
def my_custom_sql(request): cursor = connection.cursor() cursor.execute("... query ...") homecoming httpresponse(cursor.fetchone(), mimetype="application/json")
but output different in production environment.
to create work in production, changed 4th line from:
homecoming httpresponse(cursor.fetchone(), mimetype="application/json")
to:
homecoming httpresponse(json.dumps(cursor.fetchone()[0]), mimetype="application/json")
these results (i added line returns):
development environment:
using cursor.fetchone()
- correct
[{"date":"2014-06-12","count":3,"sum":3}, {"date":"2014-06-13","count":null,"sum":3}, {"date":"2014-06-14","count":null,"sum":3}, {"date":"2014-06-15","count":null,"sum":3}, {"date":"2014-06-16","count":null,"sum":3}, {"date":"2014-06-17","count":null,"sum":3}]
using json.dumps(cursor.fetchone()[0])
- incorrect: not real json.
"[{\"date\":\"2014-06-12\",\"count\":3,\"sum\":3}, \n {\"date\":\"2014-06-13\",\"count\":null,\"sum\":3}, \n {\"date\":\"2014-06-14\",\"count\":null,\"sum\":3}, \n {\"date\":\"2014-06-15\",\"count\":null,\"sum\":3}, \n {\"date\":\"2014-06-16\",\"count\":null,\"sum\":3}, \n {\"date\":\"2014-06-17\",\"count\":null,\"sum\":3}]"
production environment: (different data, ignore that)
using cursor.fetchone()
- incorrect: note python "u" strings.
[{u'date': u'2014-06-11', u'count': 4, u'sum': 4}, {u'date': u'2014-06-12', u'count': 8, u'sum': 12}, {u'date': u'2014-06-13', u'count': 7, u'sum': 19}, {u'date': u'2014-06-14', u'count': 6, u'sum': 25}, {u'date': u'2014-06-15', u'count': 1, u'sum': 26}, {u'date': u'2014-06-16', u'count': 9, u'sum': 35}, {u'date': u'2014-06-17', u'count': 4, u'sum': 39}]
using json.dumps(cursor.fetchone()[0])
- correct
[{"date": "2014-06-11", "count": 4, "sum": 4}, {"date": "2014-06-12", "count": 8, "sum": 12}, {"date": "2014-06-13", "count": 7, "sum": 19}, {"date": "2014-06-14", "count": 6, "sum": 25}, {"date": "2014-06-15", "count": 1, "sum": 26}, {"date": "2014-06-16", "count": 9, "sum": 35}, {"date": "2014-06-17", "count": 4, "sum": 39}]
how can same result in both production , development environments?
i had similar happen well. sql returning json. django on dev environment turning json dictionary containing list of lists, django in production returning dictionary containing list of strings.
the issue had different versions of psycopg2. running 2.5 in development, 2.4 in production.
check packages sure dev environment same production environment.
python json django postgresql
Comments
Post a Comment