Skip to content
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

Output to multiple files #2438

Closed
zxcat opened this issue Jun 8, 2022 · 3 comments
Closed

Output to multiple files #2438

zxcat opened this issue Jun 8, 2022 · 3 comments

Comments

@zxcat
Copy link

zxcat commented Jun 8, 2022

I need to move the values of some keys of a large JSONs input into separate files. Currently, this requires writing several jq commands for the same JSON, which is very slow with large inputs.

It would be great if jq could read and parse JSON once and then output to different files.
Alternatively, it could set ENV variables so I can write files outside of jq.

@itchyny
Copy link
Contributor

itchyny commented Jun 8, 2022

You can bind shell variables by evaluating jq output.

eval "$(jq -nr '{x:1,y:{y:2},z:{"some":"large json"}} | @sh"x=\(.x|tojson); y=\(.y|tojson); z=\(.z|tojson)"')"

echo "$x"
echo "$y"
echo "$z"

@emanuele6
Copy link
Member

Someone asked time ago on the #jq IRC channel on libera.chat

I proposed this solution:

#!/bin/sh --

jq -r '
    try (               [ .index, .isActive ] | @tsv "1\(.)"),
    try (.friends[]   | [  .name,      .age ] | @tsv "2\(.)"),
    try (.companies[] | [  .name,  .address ] | @tsv "3\(.)")
' file.jsonl \
| sed -n -e 's/^1//w file1.tsv' -e t \
         -e 's/^2//w file2.tsv' -e t \
         -e 's/^3//w file3.tsv'

N.B. if your output is not @tsv or something else that is guaranteed to be one line long, you should use something like "1\((. / "\n")[])" instead of just "1\(.)".

@zxcat
Copy link
Author

zxcat commented Jun 8, 2022

Thanx, I've tried both.
The first one is more flexible for me, coz allows to put partial JSON into a variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants