-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature request: make @sh work on objects #1947
Comments
I actually had this need as well, so I wrote a few helper functions: def to_entries_recursive(p):
if isempty(p) then
{
root: true,
type: type,
path: [],
value: to_entries_recursive([])
}
elif type == "array" or type == "object" | not then . else
to_entries | map([.value, p + [.key]] as [$val, $path] |
{
key: .key,
type: $val | type,
$path,
value: $val | to_entries_recursive($path),
}
)
end
;
def to_entries_recursive: to_entries_recursive(empty);
def flatten_tree:
def _handle_node:
if .type == "array" or .type == "object" | not then
{ (.path | join("__")): .value }
else
.value | map(_handle_node) | add
end
;
to_entries_recursive | _handle_node
;
def shell_fmt:
if type != "object" then
@sh
else
flatten_tree | to_entries | map("\(.key)=\(.value | @sh)")
end
;
Usage: jq 'shell_fmt'
{"foo": 42}
=> ["foo=42"]
jq 'shell_fmt'
{"name": {"first": "Rob", "last": "Tables", "title": "Sr."}, "kids": ["Roberta", "Bobby"]}
=> ["name__first='Rob'","name__last='Tables'","name__title='Sr.'","kids__0='Roberta'","kids__1='Bobby'"]
jq 'shell_fmt'
42
=> ["42"]
jq 'shell_fmt'
[1,3,5,7]
=> ["1 3 5 7"]
jq 'shell_fmt'
{"age": 99.9, "foo":[1,"bar",{"qux": [1,9,{"key": "huh?", "value": "idk lol"}]}], "name": "bob"}
=> ["age=99.9","foo__0=1","foo__1='bar'","foo__2__qux__0=1","foo__2__qux__1=9","foo__2__qux__2__key='huh?'","foo__2__qux__2__value='idk lol'","name='bob'"]
It's not perfect:
If you trust the source of your json and know reasonably well its structure won't have these issues, this should work in a pinch. With some more work, maybe it could be made semi-robust? Otherwise, I don't recommend it for anything important, but maybe it can give you some ideas! |
See also #789? |
Currently jq can not apply the "sh" escaping to objects:
It would be nice if it would "just work" and output assignments similar to:
The text was updated successfully, but these errors were encountered: