Xianlin
Xianlin

Reputation: 1189

jq json parser appends JSON field based on conditions

I have the below input file:

[
{
    "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"
    }
},
...
]

I would like to use jq program to parse the JSON to get the below output

[
"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
    }
},
...
]

You can see that I have inserted created_at field.

I have also added lat/long pair based on the condition of the GeoCoordinate field exist or not.

How to use jq to achieve that?

Upvotes: 0

Views: 76

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

Conditionally adding the lat/long pair should be simple. Just check if you have a GeoCoordinate value and add the pair. Your created_at property is invalid at that location, so here's the closest that we can do:

{
    created_at: now | todate,
    results: map(
        if .GeoCoordinate then
            .loc = (.GeoCoordinate | { lon: .longitude, lat: .latitude })
        else
            .
        end
    )
}

This would yield the following results:

{
  "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
      }
    }
  ]
}

Upvotes: 1

Related Questions