jq json 解析器根据条件追加 JSON 字段

jq json parser appends JSON field based on conditions

我有以下输入文件:

[
{
    "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 来实现?

有条件地添加 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
      }
    }
  ]
}