ambakshi
9/10/2014 - 12:09 AM

Using jq to modify a Json object

Using jq to modify a Json object

  $ jq  '[.[]|(select(.DeviceName == "/dev/sda1").Ebs.SnapshotId = "snap-12345678")|( select(.DeviceName == "/dev/sda1").Ebs.VolumeSize = 4) // .]' block-device-map.json

```
[
  {
    "Ebs": {
      "VolumeSize": 4,
      "SnapshotId": "snap-12345678",
      "DeleteOnTermination": true
    },
    "DeviceName": "/dev/sda1"
  },
  {
    "VirtualName": "ephemeral0",
    "DeviceName": "/dev/sdb"
  },
  {
    "VirtualName": "ephemeral1",
    "DeviceName": "/dev/sdc"
  },
  {
    "Ebs": {
      "VolumeSize": 500,
      "SnapshotId": "snap-e5133445",
      "DeleteOnTermination": false
    },
    "DeviceName": "/dev/sdf"
  }
]
```
  $ cat conf/jobs-jenkins-master-bdm.json | jq '.[0].Ebs.VolumeSize = 4' | jq '.[0].Ebs.SnapshotId = "snap-12345678"'

````
[
  {
    "DeviceName": "/dev/sda1",
    "Ebs": {
      "DeleteOnTermination": true,
      "SnapshotId": "snap-12345678",
      "VolumeSize": 4
    }
  },
  {
    "DeviceName": "/dev/sdb",
    "VirtualName": "ephemeral0"
  },
  {
    "DeviceName": "/dev/sdc",
    "VirtualName": "ephemeral1"
  },
  {
    "DeviceName": "/dev/sdf",
    "Ebs": {
      "DeleteOnTermination": false,
      "SnapshotId": "snap-e5133445",
      "VolumeSize": 500
    }
  }
]
````
// You want this:
[
  {
    "Ebs": {
      "VolumeSize": 4,
      "SnapshotId": "snap-12345678",
      "DeleteOnTermination": true
    },
    "DeviceName": "/dev/sda1"
  },
  {
    "VirtualName": "ephemeral0",
    "DeviceName": "/dev/sdb"
  },
  {
    "VirtualName": "ephemeral1",
    "DeviceName": "/dev/sdc"
  },
  {
    "Ebs": {
      "VolumeSize": 500,
      "SnapshotId": "snap-e5133445",
      "DeleteOnTermination": false
    },
    "DeviceName": "/dev/sdf"
  }
]
// Modify the following JSON object such that the SnapshotId of device /dev/sda1 is 'snap-12345678' and size is 4,
// while maintaining the structure of the of the object.
// You can't make assumptions about how it is formatted, except to say it's legal json.

[
  {
    "Ebs": {
      "VolumeSize": 32,
      "SnapshotId": "snap-ee16314e",
      "DeleteOnTermination": true
    },
    "DeviceName": "/dev/sda1"
  },
  {
    "VirtualName": "ephemeral0",
    "DeviceName": "/dev/sdb"
  },
  {
    "VirtualName": "ephemeral1",
    "DeviceName": "/dev/sdc"
  },
  {
    "Ebs": {
      "VolumeSize": 500,
      "SnapshotId": "snap-e5133445",
      "DeleteOnTermination": false
    },
    "DeviceName": "/dev/sdf"
  }
]