Skip to content

Instantly share code, notes, and snippets.

@anandsunderraman
Created November 5, 2024 14:18
Show Gist options
  • Save anandsunderraman/3dfcc4979fae7e5e09435b2d87cf38fe to your computer and use it in GitHub Desktop.
Save anandsunderraman/3dfcc4979fae7e5e09435b2d87cf38fe to your computer and use it in GitHub Desktop.
jq custom functions to convert json attributes case
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("");
def nonulls:
[ "", null, [], {} ] as $e |
walk(
if type == "object" then
with_entries(select(.value | IN($e[]) | not))
elif type == "array" then
map(select(. | IN($e[]) | not))
else . end
);

This is inspired by the original gist https://gist.github.com/reegnz/5bceb53427008a4ff9367eb8eae97b85 and jqlang/jq#104 (comment)

Copy the above .jq file to $HOME/.jq

running the command like

< sample-snake-case-request.json | jq 'map_keys(camel_to_snake) | nonulls ' > sample-camel-case-request.json

Converts the json in the file sample-snake-case-request.json, to have all its attributes converted to camel case nonulls is optional, to optionally remove attributes that are null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment