[英]Get json values using awk or jq
我的 json 文件看起來像這樣。
我有超過 5000 個文件:文件名: xxxx.json
示例文件1000.json
[
{
"gender": {
"value": "Female"
},
"age": 38.58685,
"age_group": "adult"
},
{
"gender": {
"value": "Male"
},
"age": 26.64953,
"age_group": "adult"
}
]
示例文件2000.json
[
{
"gender": {
"value": "Male"
},
"age": 63.8272,
"age_group": "adult"
},
{
"gender": {
"value": "Male"
},
"age": 11.8287,
"age_group": "child"
}
]
所需 Output 在一個文件中output.txt
1000 & Female,Male & 38,26 & adult,adult
2000 & Male,Male & 63,11 & adult,child
在jq
中可以通過一些字符串插值來實現:
$ find . -name "*.json" -exec jq -r \
'(input_filename | gsub("^\\./|\\.json$";"")) as $fname |
(map(.gender.value) | unique | join(",")) as $genders |
(map(.age|floor|tostring) | join(",")) as $ages |
(map(.age_group) | unique | join(",")) as $age_groups |
"\($fname) & \($genders) & \($ages) & \($age_groups)"' '{}' +
1000 & Female,Male & 38,26 & adult
2000 & Male & 63,11 & adult,child
input_filename
命令返回顯而易見的結果,而對於其他部分,只需從.
作為數組並將它們加入 CSV 字符串(使用join
而不是@csv
以避免添加引號)。
find
內容是為了避免jq -r '...' *.json
命令行太長的可能性,因為您說您有超過 5000 個文件。 它可能會運行jq
多次,每次使用盡可能多的文件名(尾隨+
而不是;
使得-exec
工作起來很像xargs
),而不是每個文件運行一次,以提高效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.