Environment:
- Django 1.9.10
- psycopg2 2.6.2
- PostgreSQL 9.5.4 installed via Homebrew on macOS Sierra
- Python 3.5.2 installed via Homebrew
Example model:
from django.db import models
from django.contrib.postgres.fields import JSONField
class Foo(models.Model):
data = JSONField()
When I try to create an object, everything works as expected:
from myapp.models import Foo
x = Foo()
x.data = {'some key': 'some value'}
x.save()
However, when I try to retrieve that data, the value of the .data attribute is a string:
from myapp.models import Foo
x = Foo.objects.order_by('-id')[0]
# returns "{'some key': 'some value'}"
x.data
# returns <class 'str'>
type(x.data)
My question: how do I get back the dict so I can manipulate data within the JSON field?
EDIT: Using json.loads() fails because the property names and values are enclosed in single quotes rather than double quotes:
import json
json.loads(x.data)
# JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I can use eval(), but that's obviously extremely dangerous.
json.loads()rather than eval.json.loads()to turn that string into the dict you want, but that's very odd. I have an application which usesJSONFieldand this does not happen. Also, if that was the expected behaviour, there wouldn't be much difference between usingJSONFieldorTextFieldfor example. Are you sure the object you are retrieving is exactly the same that you saved withx.data = {'some key': 'some value'}?json.loads()isn't working.