Skip to content

Instantly share code, notes, and snippets.

@johtso johtso/gist:5881137
Last active Jun 14, 2019

What would you like to do?
Django Rest Framework underscore <-> camelcase conversion
import re
from rest_framework import serializers, renderers, parsers
class JSONRenderer(renderers.JSONRenderer):
def render(self, data, *args, **kwargs):
if data:
data = recursive_key_map(underscore_to_camelcase, data)
return super(JSONRenderer, self).render(data, *args, **kwargs)
class JSONParser(parsers.JSONParser):
def parse(self, *args, **kwargs):
obj = super(JSONParser, self).parse(*args, **kwargs)
return recursive_key_map(camelcase_to_underscore, obj)
def underscore_to_camelcase(word, lower_first=True):
result = ''.join(char.capitalize() for char in word.split('_'))
if lower_first:
return result[0].lower() + result[1:]
return result
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
def camelcase_to_underscore(word):
s1 = _first_cap_re.sub(r'\1_\2', word)
return _all_cap_re.sub(r'\1_\2', s1).lower()
def recursive_key_map(function, obj):
if isinstance(obj, dict):
new_dict = {}
for key, value in obj.iteritems():
if isinstance(key, basestring):
key = function(key)
new_dict[key] = recursive_key_map(function, value)
return new_dict
if hasattr(obj, '__iter__'):
return [recursive_key_map(function, value) for value in obj]
return obj

This comment has been minimized.

Copy link

tomchristie commented Jun 28, 2013

neat 😄


This comment has been minimized.

Copy link
Owner Author

johtso commented Jun 28, 2013

Just fixed an issue with it choking on non-string keys. Not sure if it's Unicode friendly at the moment, need to pipe some through it and see where it breaks.


This comment has been minimized.

Copy link

jacobg commented Jun 28, 2013



This comment has been minimized.

Copy link

marcgibbons commented Nov 9, 2013

nice one!


This comment has been minimized.

Copy link

rockallite commented Dec 19, 2017

from django.utils.text import re_camel_case

def camel_case_to_underscore(value):
    Splits CamelCase and converts to lower case with underscores.
    return re_camel_case.sub(r'_\1', value).strip('_').lower()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.