努力解决jq中的数据格式问题。我有2个问题。
@csv
似乎不适用于我的查询。我收到错误string ("5343") cannot be csv-formatted, only array
jq命令是这个(没有| @csv
)
jq --arg LOC "$LOC" '.last_updated as $lu | .data[]|.[]| $lu, .station_id, .name, .region_id, .address, .rental_methods[]'
JSON:
{
"last_updated": 1539122087,
"ttl": 60,
"data": {
"stations": [{
"station_id": "5343",
"name": "Lot",
"region_id": "461",
"address": "Austin",
"rental_methods": [
"KEY",
"APPLEPAY",
"ANDROIDPAY",
"TRANSITCARD",
"ACCOUNTNUMBER",
"PHONE"
]
}
]
}
}
我希望输出结果为:
1539122087,5343,Lot,461,Austin,KEY:APPLEPAY:ANDROIDPAY:TRANSITCARD:ACCOUNTNUMBER:PHONE:,
答案 0 :(得分:0)
使用@csv
:
jq -r '.last_updated as $lu
| .data[][]
| [$lu, .station_id, .name, .region_id, .address, (.rental_methods | join(":")) ]
| @csv'
@csv
之前可能缺少的是在CSV记录中所需列表周围的数组构造函数。
答案 1 :(得分:0)
您可以按以下步骤维修jq过滤器:
.last_updated as $lu
| .data[][]
| [$lu, .station_id, .name, .region_id, .address,
(.rental_methods | join(":"))]
| @csv
使用您的JSON,将产生:
1539122087,"5343","Lot","461","Austin","KEY:APPLEPAY:ANDROIDPAY:TRANSITCARD:ACCOUNTNUMBER:PHONE"
...这与您所说的完全不一样。将最后一行更改为:
map(tostring) | join(",")
导致:
1539122087,5343,Lot,461,Austin,KEY:APPLEPAY:ANDROIDPAY:TRANSITCARD:ACCOUNTNUMBER:PHONE
这正是您想要的,除了标点符号外,如果需要,可以很容易地添加(例如,将+ ","
附加到上面的程序中)。