在Bash中有效地将JSON文件重写为CSV [复制]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想有效地将​​一个大的json(它总是具有相同的字段名称)重写为csv,忽略它的键。

举一个具体的例子,这里有一个大的JSON文件(tempST.json):https://gist.githubusercontent.com/pedro-roberto/b81672a89368bc8674dae21af3173e68/raw/e4afc62b9aa3092c8722cdbc4b4b4b6d5bbc1b4b/tempST.json

如果我将这个JSON中的字段timeancestorcountdescendantcount重写为CSV,我应该得到:

1535995526,1,1
1535974524,1,1
1535974528,1,2
...
1535997274,1,1

以下脚本tempSpeedTest.sh将字段timeancestorcountdescendantcount的值写入csv的每一行:

rm tempOutput.csv
jq -c '.[]' < tempST.json | while read line; do 
descendantcount=$(echo $line | jq '.descendantcount')
ancestorcount=$(echo $line | jq '.ancestorcount')
time=$(echo $line | jq '.time')
echo "${time},${ancestorcount},${descendantcount}" >> tempOutput.csv
done

但是脚本运行大约需要3分钟,这是不满意的:

>time bash tempSpeedTest.sh
real    2m50.254s
user    2m43.128s
sys 0m34.811s

什么是更快的方法来实现相同的结果?

json linux bash csv jq
1个回答
1
投票
jq -r '.[] | [.time, .descendantcount, .ancestorcount] | @csv' <tempST.json >tempOutput.csv

看看这个在https://jqplay.org/s/QJz5FCmuc9上运行

© www.soinside.com 2019 - 2024. All rights reserved.