Assert JSON keys are camelCase


This post goes over how to assert JSON keys are camelCase with JavaScript.

camelCase

Create a function that camelCases a string:

const camelCase = (string) =>
  string.replace(/[^a-zA-Z0-9]+(.)/g, (match, character) =>
    character.toUpperCase()
  );

Or use lodash:

import { camelCase } from 'lodash';

assert

Given the JSON file:

echo '{"foo":"bar"}' > data.json

Create a recursive function that asserts the JSON keys are camelCase:

import assert from 'assert';
import json from './data.json';

function assertCamelCase(object) {
  for (const [key, value] of Object.entries(object)) {
    assert.strictEqual(key, camelCase(key));

    if (value instanceof Object) {
      assertCamelCase(value);
    }
  }
}

Then call the function with the JSON data:

import data from './data.json';

assertCamelCase(data);

Demo

Check out the Replit demo:



Please support this site and join our Discord!