python根据日期将json对象分类为不同的有效载荷

时间:2019-03-30 06:22:13

标签: python json

我有一个具有以下结构的标准JSON文件:

db = {
    "db_records": [
                      {
                      "webhook": 'NA',
                      "xx": {"foo"},
                      "yy": {"otherfoo"},
                      "id": "UID1234567@2019-03-20T08:20:54.634838"
                      },
                      { ...},
                      { ...},
                      { ...},
                      { ...},
                  ]
}

我的问题是,如何根据id中的日期对该JSON进行排序?

我想到了使用以下代码创建一个从datetime中提取id的循环的方法:

for i in db['db_records']:
    conv_date = i['id'].split('@')[1].split('T')[0]
    obj_date = datetime.datetime.strptime(convo_date, '%Y-%m-%d').date()

这为我提供了每个JSON项目的日期。但是是否可以根据id中的日期将JSON对象分类为不同的有效负载?

例如:

# Everything in this payload are entries during the date: '2019-03-20'
db_payload1 = {
    "db_records": [
                      {
                      "webhook": 'NA',
                      "xx": {"foo"},
                      "yy": {"otherfoo"},
                      "id": "UID1234567@2019-03-20T08:20:54.634838"
                      },
                      { ...},


    ]
}

谢谢。

2 个答案:

答案 0 :(得分:0)

from datetime import datetime

db = {
    "db_records": [
                      {
                      "webhook": 'NA',
                      "xx": {"foo"},
                      "yy": {"otherfoo"},
                      "id": "UID1234567@2019-03-20T08:20:54.634838"
                      },
                      {...},
                      {...}
                  ]
}

def get_id_date(record):
    id_datetime = record['id'].split('@')[-1]
    return datetime.strptime(id_datetime, '%Y-%m-%dT%H:%M:%S.%f')

print(sorted(db['db_records'], key=get_id_date))

答案 1 :(得分:0)

您可以使用re.search搜索日期,使用datetime.datetime.strptime将字符串解析为日期时间格式,然后按.date()进行排序:

from re import search
from datetime import datetime
from pprint import pprint

db = {
    "db_records": [
        {
            "webhook": "NA",
            "xx": {"foo"},
            "yy": {"otherfoo"},
            "id": "UID1234567@2019-03-20T08:20:54.634838",
        },
        {
            "webhook": "NA",
            "xx": {"foo"},
            "yy": {"otherfoo"},
            "id": "UID1234567@2019-03-19T08:20:54.634838",
        },
        {
            "webhook": "NA",
            "xx": {"foo"},
            "yy": {"otherfoo"},
            "id": "UID1234567@2019-03-18T08:20:54.634838",
        },
    ]
}

sort_key = lambda x: datetime.strptime(
    search(r"\d{4}-\d{2}-\d{2}", x["id"]).group(), "%Y-%m-%d"
).date()

pprint(sorted(db["db_records"], key=sort_key))

哪些输出:

[{'id': 'UID1234567@2019-03-18T08:20:54.634838',
  'webhook': 'NA',
  'xx': {'foo'},
  'yy': {'otherfoo'}},
 {'id': 'UID1234567@2019-03-19T08:20:54.634838',
  'webhook': 'NA',
  'xx': {'foo'},
  'yy': {'otherfoo'}},
 {'id': 'UID1234567@2019-03-20T08:20:54.634838',
  'webhook': 'NA',
  'xx': {'foo'},
  'yy': {'otherfoo'}}]