Skip to content

Instantly share code, notes, and snippets.

@rouge8
Created April 23, 2013 16:28
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rouge8/5445149 to your computer and use it in GitHub Desktop.
Save rouge8/5445149 to your computer and use it in GitHub Desktop.
Django REST Framework JSON Field
import json
from rest_framework import serializers
class JSONField(serializers.WritableField):
def to_native(self, obj):
return json.dumps(obj)
def from_native(self, value):
return json.loads(value)
@kot-behemoth
Copy link

I'd also maybe add a try/catch to from_native, so that serialisation wouldn't fail pre-emptively, e.g.:

def from_native(self, value):
    try:
        val = json.loads(value)
    except TypeError:
        raise serializers.ValidationError(
            "Could not load json <{}>".format(value)
        )
    return val

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment