I provide you with 3 jq lib functions that will help you in converting between snake_case and CamelCase.
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
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("");
Thanks! You rock!