Skip to content

Renaming and Restructuring JSON Keys ​

Transform JSON structures by renaming keys, reshaping objects, and converting between formats using fx.

Rename a Single Key ​

Change one key name:

bash
cat data.json | fx '{...x, fullName: x.name}' 'x => {delete x.name; return x}'

Input:

json
{
  "name": "Alice",
  "age": 25
}

Output:

json
{
  "age": 25,
  "fullName": "Alice"
}

Rename Multiple Keys ​

Apply a mapping of old to new names:

bash
cat data.json | fx 'x => {
  const map = {name: "fullName", age: "years"};
  return Object.fromEntries(
    Object.entries(x).map(([k, v]) => [map[k] || k, v])
  );
}'

Output:

json
{
  "fullName": "Alice",
  "years": 25
}

Rename Keys in Array of Objects ​

Transform all objects in an array:

bash
cat users.json | fx 'map(u => ({
  id: u.id,
  fullName: u.name,
  emailAddress: u.email
}))'

Output:

json
[
  {
    "id": 1,
    "fullName": "Alice",
    "emailAddress": "alice@example.com"
  },
  {
    "id": 2,
    "fullName": "Bob",
    "emailAddress": "bob@example.com"
  }
]

Convert snake_case to camelCase ​

Transform all keys automatically:

bash
cat data.json | fx 'x => {
  const toCamel = s => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
  const convert = obj => {
    if (Array.isArray(obj)) return obj.map(convert);
    if (obj && typeof obj === "object") {
      return Object.fromEntries(
        Object.entries(obj).map(([k, v]) => [toCamel(k), convert(v)])
      );
    }
    return obj;
  };
  return convert(x);
}'

Input:

json
{
  "user_name": "alice",
  "created_at": "2024-01-15"
}

Output:

json
{
  "userName": "alice",
  "createdAt": "2024-01-15"
}

Convert camelCase to snake_case ​

Reverse transformation:

bash
cat data.json | fx 'x => {
  const toSnake = s => s.replace(/[A-Z]/g, c => "_" + c.toLowerCase());
  const convert = obj => {
    if (Array.isArray(obj)) return obj.map(convert);
    if (obj && typeof obj === "object") {
      return Object.fromEntries(
        Object.entries(obj).map(([k, v]) => [toSnake(k), convert(v)])
      );
    }
    return obj;
  };
  return convert(x);
}'

Restructure Nested Objects ​

Flatten or nest as needed:

bash
cat data.json | fx 'x => ({
  id: x.id,
  name: x.user.name,
  city: x.user.address.city
})'

Input:

json
{
  "id": 1,
  "user": {
    "name": "Alice",
    "address": {
      "city": "NYC"
    }
  }
}

Output:

json
{
  "id": 1,
  "name": "Alice",
  "city": "NYC"
}

Add Prefix to All Keys ​

Namespace your keys:

bash
cat data.json | fx 'x => Object.fromEntries(
  Object.entries(x).map(([k, v]) => ["user_" + k, v])
)'

Output:

json
{
  "user_name": "Alice",
  "user_age": 25
}

Remove Specific Keys ​

Filter out unwanted fields:

bash
cat data.json | fx 'x => {
  const {password, secret, ...rest} = x;
  return rest;
}'

Or for multiple objects:

bash
cat users.json | fx 'map(({password, ...rest}) => rest)'