【发布时间】:2021-02-13 18:19:16
【问题描述】:
有没有办法只加载包含来自 json 的特定键值的对象?
我所做的步骤:
response = requests.get(URL, headers={'token': TOKEN}, verify=False)
meta_json = json.loads(response.content)
meta_json 看起来像这样:
{
"count": 264428,
"data": [
{
"calculation_date": "2020-04-09T12:33:05.814107",
"name": "Felix",
"age": 12
},
{
"calculation_date": "2020-03-09T12:33:05.814107",
"name": "Max",
"age": 18
},
{
"calculation_date": "2020-04-09T12:33:15.814207",
"name": "John",
"age": 25
}
],
"links": {
"first": "random",
"last": "second"
}
}
但我只想查看四月,meta_json 应该是这样的:
{
"count": 264428,
"data": [
{
"calculation_date": "2020-04-09T12:33:05.814107",
"name": "Felix",
"age": 12
},
{
"calculation_date": "2020-04-09T12:33:15.814207",
"name": "John",
"age": 25
}
],
"links": {
"first": "random",
"last": "second"
}
}
如何做到这一点?
【问题讨论】:
-
meta_json = {k: v if k != "data" else [i for i in v if datetime.fromisoformat(i["calculation_date"]).month == 4] for k, v in meta_json.items()}。文档:fromisoformat()。顺便说一句,你可以使用response.json()。