我有以下输入文件:
[
{
"macAddress": "22:00:10:21:ca:54",
"GeoCoordinate": {
"latitude": 1.2345,
"longitude": 123.4567,
"unit": "DEGREES"
}
},
{
"macAddress": "44:00:10:21:ca:14"
},
{
"macAddress": "33:00:11:21:ca:54",
"GeoCoordinate": {
"latitude": 2.1345544523,
"longitude": 123.45678,
"unit": "DEGREES"
}
},
...
]
我想使用jq
程序来解析JSON以获得以下输出
[
"created_at": "2016-04-13T14:50:03+0800",
{
"macAddress": "22:00:10:21:ca:54",
"GeoCoordinate": {
"latitude": 1.2345,
"longitude": 123.4567,
"unit": "DEGREES"
},
"loc": {
"lon": 123.4567,
"lat": 1.2345
}
},
{
"macAddress": "44:00:10:21:ca:14"
},
{
"macAddress": "33:00:11:21:ca:54",
"GeoCoordinate": {
"latitude": 2.1345544523,
"longitude": 123.45678,
"unit": "DEGREES"
},
"loc": {
"lon": 123.45678,
"lat": 2.1345544523
}
},
...
]
您可以看到我已插入created_at
字段。
我还根据GeoCoordinate
字段的条件添加了lat / long对。
如何使用jq
来实现这一目标?
答案 0 :(得分:1)
有条件地添加lat / long对应该很简单。只需检查您是否有GeoCoordinate
值并添加该对。您的created_at
媒体资源在该位置无效,因此这是我们最接近的地方:
{
created_at: now | todate,
results: map(
if .GeoCoordinate then
.loc = (.GeoCoordinate | { lon: .longitude, lat: .latitude })
else
.
end
)
}
这将产生以下结果:
{
"created_at": "2016-04-19T20:09:35Z",
"results": [
{
"macAddress": "22:00:10:21:ca:54",
"GeoCoordinate": {
"latitude": 1.2345,
"longitude": 123.4567,
"unit": "DEGREES"
},
"loc": {
"lon": 123.4567,
"lat": 1.2345
}
},
{
"macAddress": "44:00:10:21:ca:14"
},
{
"macAddress": "33:00:11:21:ca:54",
"GeoCoordinate": {
"latitude": 2.1345544523,
"longitude": 123.45678,
"unit": "DEGREES"
},
"loc": {
"lon": 123.45678,
"lat": 2.1345544523
}
}
]
}