使用JQ解析对象的JSON数组,使用select匹配object元素中的指定键值,然后转换为CSV [英] Use JQ to parse JSON array of objects, using select to match specified key-value in the object element, then convert to CSV
本文介绍了使用JQ解析对象的JSON数组,使用select匹配object元素中的指定键值,然后转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用JQ解析对象的JSON数组,使用select匹配object元素中的指定键值,然后转换为CSV.
Use JQ to parse JSON array of objects, using select to match specified key-value in the object element, then convert to CSV.
数据源:
{
"Other": [],
"Objects": [
{
"ObjectElementName": "Test 123",
"ObjectElementArray": [],
"ObjectElementUnit": "1"
},
{
"ObjectElementName": "Test ABC 1",
"ObjectElementArray": [],
"ObjectElementUnit": "2"
},
{
"ObjectElementName": "Test ABC 2",
"ObjectElementArray": [],
"ObjectElementUnit": "5"
}
],
"Language": "en-US"
}
要提取的JQ命令
jq -r '.Objects[] | select(.ObjectElementName | contains("ABC"))'
给定的输出(仅单个对象,没有JSON结构)...
{
"ObjectElementName": "Test ABC 1",
"ObjectElementArray": [],
"ObjectElementUnit": "2"
}
{
"ObjectElementName": "Test ABC 2",
"ObjectElementArray": [],
"ObjectElementUnit": "5"
}
此格式所需的输出(在对象上方保留JSON数组)
{
"Other": [],
"Objects": [
{
"ObjectElementName": "Test ABC 1",
"ObjectElementArray": [],
"ObjectElementUnit": "2"
},
{
"ObjectElementName": "Test ABC 2",
"ObjectElementArray": [],
"ObjectElementUnit": "5"
}
],
"Language": "en-US"
}
需要此格式的输出,以便可以执行CSV转换
in2csv -f json --key Objects > output.csv
需要输出CSV
ObjectElementName,ObjectElementUnit
Test ABC 1,2
Test ABC 2,5
推荐答案
如果要使用CSV,则应该使用jq的@csv
过滤器,该过滤器实质上可以保证有效的CSV输出.例如,使用您的输入:
If you want CSV, you should probably use jq's @csv
filter, which essentially guarantees valid CSV output. For example, using your input:
jq -r '
["ObjectElementName","ObjectElementUnit"],
(.Objects[]
| select(.ObjectElementName | test("ABC"))
| [.ObjectElementName,.ObjectElementUnit] )
| @csv' input.json
产生:
"ObjectElementName","ObjectElementUnit"
"Test ABC 1","2"
"Test ABC 2","5"
但是,如果您愿意冒险,可以将@csv
替换为join(",")
,在当前情况下,这将导致:
However, if you're willing to take the risks, you could replace @csv
by join(",")
, which in the present case would result in:
ObjectElementName,ObjectElementUnit
Test ABC 1,2
Test ABC 2,5
这篇关于使用JQ解析对象的JSON数组,使用select匹配object元素中的指定键值,然后转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文