Home > front end >  Jsonpath or jmespath to get just id if created
Jsonpath or jmespath to get just id if created

Time:08-24

{
  "data": [


    {
      "compartment-id": "ocid1.compartment.oc1..42949232syq",
      "defined-tags": {
        "Oracle-Tags": {
          "CreatedBy": "svc-1",
          "CreatedOn": "2022-08-19T05:48:06.460Z"
        }


      },
      "display-name": "service1-ic-20220819T054722",
      "freeform-tags": {},
      "id": "ocid1.instanceconfiguration.oc1.me-jeddah-1.adhk32khsaq",
      "time-created": "2022-08-19T05:48:06.586000 00:00"
    },
    
    {
      "compartment-id": "ocid1.compartment.oc1..aaaahsa232dvsanmsakhfyq",
      "defined-tags": {
        "Oracle-Tags": {
          "CreatedBy": "svc-1",
          "CreatedOn": "2022-08-16T05:47:49.269Z"
        }
      },
      "display-name": "service2-ic-20220819T054705",
      "freeform-tags": {},
      "id": "ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa",
      "time-created": "2022-08-16T05:47:49.546000 00:00"
    } ,

  {
      "compartment-id": "ocid1.compartment.oc1..aaaahsa232dvsanmsakhfyq",
      "defined-tags": {
        "Oracle-Tags": {
          "CreatedBy": "svc-1",
          "CreatedOn": "2022-08-15T05:47:49.269Z"
        }
      },
      "display-name": "service2-ic-20220819T054705",
      "freeform-tags": {},
      "id": "ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa",
      "time-created": "2022-08-15T05:47:49.546000 00:00"
    }

]
    
    
}

Above is json array, I want to get list of "id" if any time-created is before 2022-08-19, it means we have in our array two elements. So we should return

[ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa, ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa]

If this is doable using shell script? or there is way to use jmespath to return this values.

CodePudding user response:

Lexicographical ordering in Python should do the job. For example,

shell> cat get_id.py
#!/usr/bin/python3
import json
import jmespath


compareDate = '2022-08-19'

f = open('data.json', 'r')
data_json = json.loads(f.read())
# print(json.dumps(data_json, indent=2))

ids = jmespath.search(f'data[?"time-created" < `{compareDate}`].id', data_json)
print(*ids, sep='\n')

gives

shell> ./get_id.py
ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa
ocid1.instanceconfiguration.oc1.me-jeddah-1.aaasafhsknvlsasrhv4w5lgcfyuvgtbsofd2wuk7c6yh2rgigx2xfaa

See:

  • Related