英文:
How can I use jq to filter only certain fields of the original JSON into an CSV?
问题
我说此Stack Overflow答案使用简单的jq命令将JSON转换为CSV文件,但我需要进一步改进它。
假设我有以下JSON:
[
{
"name": "foo",
"env": "dev",
"version": "1.24"
},
{
"name": "bar",
"env": "staging",
"version": "1.21"
},
{
"name": "boo",
"env": "prod",
"version": "1.23"
},
{
"name": "far",
"env": "prod",
"version": "1.24"
}
]
如何只创建包含"name"和"version"字段的CSV?
我当前的命令是:
jq -r '(map(keys) | add | unique) as $cols | map(.[] | {name, version} as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'
这不起作用。有人可以提供一些帮助吗?
谢谢!
英文:
I say this stack overflow anser with a simple jq command to convert a JSON to a csv file, but I need to improve it further.
Say I have the following JSON:
[
{
"name": "foo",
"env": "dev",
"version": "1.24"
},
{
"name": "bar",
"env": "staging",
"version": "1.21"
},
{
"name": "boo",
"env": "prod",
"version": "1.23"
},
{
"name": "far",
"env": "prod",
"version": "1.24"
}
]
How does one create the CSV with only the "name" and "version" fields?
My current command is:
jq -r '(map(keys) | add | unique) as $cols | map(.[] | {name, version} as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'
This is not working. Can anyone provide some help?
Thanks!
答案1
得分: 4
如果你已经知道两个列名,你可以直接使用`.name`和`.version`来提取它们:
<file jq -r '[ "name", "version" ], ( .[] | [ .name, .version ] ) | @csv'
你也可以使用你的`$cols`变量,这样列名只会出现一次:
<file jq -r '[ "name", "version" ] as $cols | $cols, ( .[] | [ .[$cols[]] ] ) | @csv'
或者动态导入它们,例如使用`--args`:
<file jq -r '$ARGS.positional, ( .[] | [ .[$ARGS.positional[]] ] ) | @csv'
--args name version
输出:
"name","version"
"foo","1.24"
"bar","1.21"
"boo","1.23"
"far","1.24"
英文:
If you know the two column names anyway, you could simply extract them directly using .name
and .version
:
<file jq -r '["name", "version"], (.[] | [.name, .version]) | @csv'
You can also use your $cols
variable, so the names only appear once:
<file jq -r '["name", "version"] as $cols | $cols, (.[] | [.[$cols[]]]) | @csv'
Or import them dynamically, e.g. using --args
:
<file jq -r '$ARGS.positional, (.[] | [.[$ARGS.positional[]]]) | @csv' \
--args name version
Output:
"name","version"
"foo","1.24"
"bar","1.21"
"boo","1.23"
"far","1.24"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论