How to Convert JSON Keys Between camelCase and snake_case

4 min read

Converting JSON keys between naming conventions is essential when your frontend and backend use different styles.

JavaScript: snake_case → camelCase

function camelizeKeys(obj) {
  if (Array.isArray(obj)) return obj.map(camelizeKeys);
  if (obj && typeof obj === 'object') {
    return Object.fromEntries(
      Object.entries(obj).map(([k, v]) => [
        k.replace(/_([a-z])/g, (_, c) => c.toUpperCase()),
        camelizeKeys(v)
      ])
    );
  }
  return obj;
}

Python: camelCase → snake_case

import re
def snake_keys(obj):
    if isinstance(obj, dict):
        return {re.sub(r'(?<=[a-z])(?=[A-Z])', '_', k).lower(): snake_keys(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [snake_keys(i) for i in obj]
    return obj

Online Tools

JSON keys to camelCase or JSON keys to snake_case.