← Blog · · ConvertCaseHQ Team · 7 min read

Fixing camelCase JSON: Converting API Payloads to snake_case

To convert a camelCase JSON payload to snake_case, parse it, walk the result recursively, and rename every object key with a function that splits at each lowercase-to-uppercase boundary and at the end of each acronym, then lowercases the pieces and joins them with underscores. Values stay as they are, and arrays are walked but never renamed. Do it once, where requests enter your backend, and the rest of your Python or Ruby code never sees a camelCase key.

The splitting function is where most snippets go wrong, so that's where we'll start. After that you'll find a JavaScript version, a Python version, the edge cases that break naive code, and what the popular libraries actually do with them.

Why the one-line regex turns userID into user_i_d

The version you'll see most often puts an underscore in front of every capital letter:

key.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());

It handles firstName fine and falls apart as soon as an acronym or a leading capital shows up:

KeyOne-line regexWhat you wanted
userIDuser_i_duser_id
XMLHttpRequest_x_m_l_http_requestxml_http_request
UserName_user_nameuser_name

The fix is two rules instead of one. First, split where a run of capitals ends and a capitalized word begins, so XMLHttp becomes XML_Http. Then split where a lowercase letter or a digit meets a capital, so userId becomes user_Id. Lowercase the result and you're done. Python's inflection package and Rails' underscore use the same pair of rules, and our case converter applies a Unicode-aware version of them when you click snake_case, so you can paste a single awkward key there to see how it splits. (Paste one key at a time: the converter treats everything you paste as one name.)

Converting camelCase JSON keys to snake_case in JavaScript

This version works in Node and in the browser, with no dependencies:

// userId -> user_id, userID -> user_id, XMLHttpRequest -> xml_http_request
function toSnake(key) {
  return key
    .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") // end of an acronym: XMLHttp -> XML_Http
    .replace(/([a-z0-9])([A-Z])/g, "$1_$2")    // lower or digit, then capital: userId -> user_Id
    .toLowerCase();
}

function isPlainObject(value) {
  if (value === null || typeof value !== "object") return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}

// Renames keys at every depth. Keys listed in `skip` keep their contents as they are.
function snakeKeys(value, skip = new Set()) {
  if (Array.isArray(value)) return value.map((item) => snakeKeys(item, skip));
  if (!isPlainObject(value)) return value;

  const out = new Map();
  for (const [key, child] of Object.entries(value)) {
    const newKey = toSnake(key);
    if (out.has(newKey)) {
      throw new Error('Two keys become "' + newKey + '" (one of them is "' + key + '")');
    }
    out.set(newKey, skip.has(key) ? child : snakeKeys(child, skip));
  }
  return Object.fromEntries(out);
}

const data = snakeKeys(JSON.parse(requestBody), new Set(["metadata"]));

A few choices in there are deliberate:

  • Only plain objects are renamed. JSON.parse only ever produces plain objects, but helpers like this tend to get reused on objects built in code, and you don't want a Date or a class instance taken apart.
  • Collisions throw. A payload that contains both userId and user_id would otherwise lose one of them without a word.
  • Some subtrees are left alone. More on that under edge cases.
  • Object.fromEntries builds the result. If a client sends a key called __proto__, it becomes an ordinary property. Plain assignment (out[newKey] = …) would set the new object's prototype instead.

If you'd rather rename while parsing, JSON.parse takes a reviver function. It visits the innermost values first, so every nested object has already been renamed by the time its parent comes through:

const data = JSON.parse(requestBody, (key, value) =>
  isPlainObject(value)
    ? Object.fromEntries(Object.entries(value).map(([k, v]) => [toSnake(k), v]))
    : value
);

It's compact, but you give up the skip list and the collision check. By the time the reviver sees metadata, everything inside it has already been renamed.

The same conversion in Python

import json
import re

ACRONYM_END = re.compile(r"([A-Z]+)([A-Z][a-z])")  # XMLHttp -> XML_Http
CASE_CHANGE = re.compile(r"([a-z0-9])([A-Z])")     # userId  -> user_Id
OVERRIDES = {"orderIDs": "order_ids"}              # keys no rule can guess

def to_snake(key: str) -> str:
    if key in OVERRIDES:
        return OVERRIDES[key]
    key = ACRONYM_END.sub(r"\1_\2", key)
    key = CASE_CHANGE.sub(r"\1_\2", key)
    return key.lower()

def snake_keys(value, skip=frozenset()):
    if isinstance(value, list):
        return [snake_keys(item, skip) for item in value]
    if isinstance(value, dict):
        out = {}
        for key, child in value.items():
            new_key = to_snake(key)
            if new_key in out:
                raise ValueError(f"two keys become {new_key!r} (one is {key!r})")
            out[new_key] = child if key in skip else snake_keys(child, skip)
        return out
    return value

data = snake_keys(json.loads(raw), skip={"metadata"})

Python's json module can also do the renaming during parsing. The object_pairs_hook argument is called for every JSON object as it's decoded, with its key/value pairs in order, so it even catches duplicate keys in the original text that a plain dict would quietly collapse (see the json module documentation):

def snake_pairs(pairs):
    out = {}
    for key, value in pairs:
        new_key = to_snake(key)
        if new_key in out:
            raise ValueError(f"two keys become {new_key!r}")
        out[new_key] = value
    return out

data = json.loads(raw, object_pairs_hook=snake_pairs)

In Ruby on Rails, ActiveSupport already covers the recursion: hash.deep_transform_keys(&:underscore) renames keys in nested hashes, including hashes inside arrays, and underscore splits acronyms with the same two rules.

Edge cases worth a test each

Plural acronyms

userID comes out right, but orderIDs becomes order_i_ds. That isn't a bug in the code above: no rule can tell "IDs" from "I" plus "Ds". Every library we tried (snakecase-keys, change-case, humps, pyhumps, inflection, Pydantic's to_snake and Rails' underscore) gives the same answer. Keep a small override table, like OVERRIDES in the Python version, for the handful of keys your API has like this.

Numbers

Our rules keep a digit attached to the word before it: address2Line becomes address2_line. Lodash's snakeCase and Pydantic's to_snake give address_2_line instead. Neither is wrong, but your Python field names have to match whatever the converter produces, so pick one behavior and write it down.

Leading underscores

MongoDB's _id and GraphQL's __typename pass through the functions above unchanged. The npm packages snakecase-keys and change-case strip them, so _id arrives as id unless you exclude the key (snakecase-keys) or set the prefixCharacters option (change-case).

Keys that are really data

Some objects are maps, not records: translations keyed by en-US, prices keyed by SKU, settings keyed by whatever the user typed. A user ID like a1B2 would be rewritten as a1_b2, and now it matches nothing. That's what the skip list is for. Name every map-like field in your API and leave its contents alone.

Round trips aren't lossless

Convert userID to user_id and back, and you get userId. If the client needs its exact key names back in the response, rename by declared field instead of by rule, which is where Pydantic helps.

Should you use a library instead?

Often, yes, as long as you know its quirks. We ran the same keys through the common ones (versions as tested):

LibraryNested keysuserID_id
snakecase-keys 9 (npm)Yes, by defaultuser_idid
humps 2 (npm), decamelizeKeysYesuser_i_d_id
change-case 5 (npm), change-case/keysTop level only, unless you pass a depthuser_idid
pyhumps 3.8 (PyPI), humps.decamelizeYesuser_id_id

In a Python API built on Pydantic, you may not need to rename anything. Declare snake_case fields, let an alias generator accept the camelCase names, and dump with aliases when you respond:

from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel

class Order(BaseModel):
    model_config = ConfigDict(alias_generator=to_camel)
    user_id: int = Field(alias="userID")   # explicit alias wins over the generator
    shipping_address: str                  # accepted as "shippingAddress"

order = Order.model_validate({"userID": 42, "shippingAddress": "1 Main St"})
order.user_id                    # 42
order.model_dump(by_alias=True)  # {'userID': 42, 'shippingAddress': '1 Main St'}

Because each field declares its outside name, nothing is guessed and the round trip is exact. That's our pick whenever the payload has a schema. Keep the recursive function for free-form JSON that doesn't. If you're unsure why the Python side insists on snake_case at all, our guide to PEP 8 naming covers it.

A checklist before you ship

  1. Convert in exactly one place: the request parser, middleware or serializer, not scattered through handlers.
  2. Unit-test the key function with userId, userID, XMLHttpRequest, address2Line, _id and one key for every acronym your API uses.
  3. Decide how digits split and document it next to the function.
  4. List the map-like fields to skip.
  5. Fail loudly on collisions instead of letting one key overwrite another.
  6. Run a real payload through it and compare the key lists before and after with our text diff tool. A stray i_d stands out immediately.

© 2026 ConvertCaseHQ. All rights reserved.