Skip to content

Instantly share code, notes, and snippets.

@mfridman
Forked from reegnz/README.md
Created November 15, 2022 01:56
Show Gist options
  • Save mfridman/711f1ed318245d32fd3256089097d944 to your computer and use it in GitHub Desktop.
Save mfridman/711f1ed318245d32fd3256089097d944 to your computer and use it in GitHub Desktop.
CamelCase <--> snake_case conversion in jq

CamelCase <--> snake_case conversion with jq

tl;dr

I provide you with 3 jq lib functions that will help you in converting between snake_case and CamelCase.

The interface

I want to change keys in my json from camelcase to snake_case.

{
  "SomeKey": {
    "NestedKey": "NestedValue",
    "NestedList": [
      {
        "NestedKey": "NestedValue"
      },
      {
        "NestedKey": "NestedValue"
      },
      {
        "NestedKey": "NestedValue"
      }
    ]
  }
}

It would be nice to do this with a simple command, something like this:

<my.json | jq 'map_keys(camel_to_snake)' > my_snake.json

This would result in the following output:

{
  "some_key": {
    "nested_key": "NestedValue",
    "nested_list": [
      {
        "nested_key": "NestedValue"
      },
      {
        "nested_key": "NestedValue"
      },
      {
        "nested_key": "NestedValue"
      }
    ]
  }
}

We also expect that we get the same CamelCase json back if we convert back the snake_case version.

diff <(<my.json jq) <(<my.json | jq 'map_keys(camel_to_snake)|map_keys(snake_to_camel)'); echo $?
0

The solution

Once you put the following functions into $HOME/.jq file the above command will just work!

def map_keys(mapper):
  walk(
    if type == "object"
    then
      with_entries({
        key: (.key|mapper),
	value
      })
    else .
    end
  );

def camel_to_snake:
  [
    splits("(?=[A-Z])")
  ]
  |map(
    select(. != "")
    | ascii_downcase
  )
  | join("_");

def snake_to_camel:
  split("_")
  | map(
    split("")
    | .[0] |= ascii_upcase
    | join("")
  )
  | join("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment