Reputation: 6662
I have some json data and I want to interactively query it with fzf and jq, by sending the data through stdin and typing the jq query into the fzf query box.
My attempt so far is showing one result in the box, but editing the contents of the query box turns the results blank instead.
fzf-tmux --preview 'jq "$@" <<< {}' <<<'[{"x": 1}, {"y": 2}]'
Upvotes: 1
Views: 2381
Reputation: 20822
A recent Hacker News post about using fzf
as a REPL had me thinking it would be interesting to live-edit jq
filters as well. Using the base implementation from that article, I ended up with:
echo '' | fzf --print-query --preview='jq {q} <(echo "[{\"x\": 1}, {\"y\": 2}]")'
You can clean up the quoting a bit, at the expense of some verbosity, by changing it to:
(export json='[{"x": 1}, {"y": 2}]'; echo '' | fzf --print-query --preview='jq {q} <(echo $json)')
or (somewhat safer for unvalidated input):
(export json='[{"x": 1}, {"y": 2}]'; echo '' | fzf --print-query --preview='jq {q} <(printf "%s" "$json")')
Final example, using the StackExchange API to retrieve this post:
(export json=$(curl -s --compressed -H "Accept-Encoding: GZIP" "https://api.stackexchange.com/2.2/posts/56744579?site=stackoverflow&filter=withbody"); echo '' | fzf --print-query --preview-window=wrap --preview='filter={q}; jq -M -r "${filter}" <(printf "%s" "$json")')</code>
One more example, added around 18 months later. This is the same as the previous example, but for the Fish shell. It also uses httpie
to clean things up as well, since httpie
automatically handles things like the encoding/compression. I also left in the color output on this one:
begin
set -lx jq_url 'https://api.stackexchange.com/2.2/posts/56744579?site=stackoverflow&filter=withbody'
echo '' | fzf --print-query --preview='set -x q {q}; jq -C {q} (http -b GET "$jq_url" | psub)'
end
Note: The begin
/end
block is only there to keep variables in a local scope. They really aren't required for the example to work, just to keep from polluting the namespace.
Upvotes: 5
Reputation: 116957
If you're expecting $@
to be expanded by the shell, then the simple fix is to modify the quoting:
fzf-tmux --preview 'jq '"$@"' <<< {}'
If on the other hand, you want to use the {q}
feature of fzf, which seems to be the case, then you may be out of luck, though whether that's because of a bug in fzf, or some incompatibility between jq and fzf, I cannot tell.
Let's suppose $JSON is a file containing a single JSON array or object. Then when running the following, you'll see the paths on the LHS, and the value at the selected path on the RHS:
jq -rc paths "$JSON" |
fzf-tmux --preview 'x={}; jq "getpath($x)" '"$JSON"
Upvotes: 2