0

JSON output:

"machines": {
              "machines-xyz-123": {
                         "vm": {
                                  "id": "compute1234",
                                  "createTimestamp": "2020-11-15T14:44:02.272908941Z",
                                  "status": "running"
                                }
              "machines-tyu-567": {
                        "vm": {
                                  "id": "compute23456",
                                  "createTimestamp": "2020-11-15T18:18:22.412021105Z",
                                  "status": "running"
                              }
                        }
            }

Machine ID changes dynamically each time, I am able to get the VM ID and timestamp of each machine with below code:

machine_list = json_output[machines]
key_list = list(machines.keys())
count = len(machine_list)

for i in range (count):
     id = json_output['machines'][key_list[i]]['vm']['id']
     date = json_output['machines'][key_list[i]]['vm']['creationTimestamp']

I need to do 2 operations from the JSON output further:

1.) Need to form a new JSON dictionary with 'id' value as key and 'timestamp' value as value of the id key

2.) Need to retrieve the id based on the latest timestamp value from the JSON dictionary

Any help will be appreciated.

Automation Engr
  • 444
  • 2
  • 4
  • 26

1 Answers1

1

not sure i understand your question

import json
my_dict = {}
my_dict[id] = timestamp
my_json = json.dumps(my_dict)   #to create a json and save it as a file
out_file = open(my_path,"w")
out_file.write(my_json)
out_file.close()

#to compare between dates see https://stackoverflow.com/questions/8142364/how-to-compare-two-dates
max_date = 0
max_id = 0
for id in my_dict:
    if my_dict[id]>max_date: # use date compare method
        max_date = my_dict[id]
        max_id = id


trigonom
  • 528
  • 4
  • 9