【问题标题】:Python, JSON: Form new JSON dict having id & timestamp & retrieve the id based on the latest timestamp value from the new JSON dictionaryPython,JSON:形成具有 id 和时间戳的新 JSON 字典并根据新 JSON 字典中的最新时间戳值检索 id
【发布时间】:2020-11-15 20:55:15
【问题描述】:

JSON 输出:

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

机器ID每次都会动态变化,我可以通过以下代码获取每台机器的VM ID和时间戳:

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']

我需要进一步从 JSON 输出中执行 2 个操作:

1.) 需要形成一个新的 JSON 字典,以 'id' 值作为键和 'timestamp' 值作为 id 键的值

2.) 需要根据最新的时间戳值从 JSON 字典

任何帮助将不胜感激。

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

    不确定我是否理解您的问题

    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
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2014-05-01
      相关资源
      最近更新 更多