我有我想转换成使用一个shell脚本jq一个CSV文件JSON文件。我想从这个整个JSON文件中创建一个单行。我必须从值中获取价值。该行输出应该是这样的
空,642,642,412,0,NULL,NULL
Here is my JSON file
{
"data": [
{
"name": "exits",
"period": "lifetime",
"values": [
{
"value": {}
}
],
"title": "Exits",
"description": "Number of times someone exited the carousel"
},
{
"name": "impressions",
"period": "lifetime",
"values": [
{
"value": 642
}
],
"title": "Impressions",
"description": "Total number of times the media object has been seen"
},
{
"name": "reach",
"period": "lifetime",
"values": [
{
"value": 412
}
],
"title": "Reach",
"description": "Total number of unique accounts that have seen the media object"
},
{
"name": "replies",
"period": "lifetime",
"values": [
{
"value": 0
}
],
"title": "Replies",
"description": "Total number of replies to the carousel"
},
{
"name": "taps_forward",
"period": "lifetime",
"values": [
{
"value": {}
}
],
"title": "Taps Forward",
"description": "Total number of taps to see this story's next photo or video"
},
{
"name": "taps_back",
"period": "lifetime",
"values": [
{
"value": {}
}
],
"title": "Taps Back",
"description": "Total number of taps to see this story's previous photo or video"
}
]
}
嗨尝试使用此命令jq:
.data | map(.values[].value) | @csv
这是给下面的输出: jq:错误(在:70):对象({})不在csv行有效 退出状态5
所以,当我得到这个空JSON对象是反映一个错误。
请帮忙!!
该行输出应该是这样的
空,642,642,412,0,NULL,NULL
分析解答
如果你没有@csv一部分运行的命令,你会看到输出是:
[
{},
642,
412,
0,
{},
{}
]
通过用"null"更换空物体:(长度== 0)
jq '.data | map(.values[].value) | map(if (length == 0 ) then "null" else . end) | @csv'
Output:
"\"null\",642,412,\"null\",\"null\",\"null\""
每从@aaron建议(见注释)。下面就可以产生需要的输出,无需额外post-processing。免责声明:这不是我的jq 1.5工作,但jqplay正在与jq 1.6。
jq --raw-output '.data | map(.values[].value) | map(if (length == 0 ) then "null" else . end) | join(",")'
Output:
null,642,412,null,null,null