如何保留JSON中orbiting_body为Earth且approach_date最小的对象
解决方法:过滤并保留最早的Earth接近记录
嘿,我来帮你搞定这段代码!先理清楚你的需求:你要遍历每个天体数据,先把close_approach_data里orbiting_body不为Earth的条目去掉,然后在剩下的Earth条目中保留approach_date最早的那个,最后把close_approach_data从数组改成单个对象。(注意:你给出的期望结果里写的是Mars,这和需求描述矛盾,我按照你文字描述的需求来修正代码)
原始数据
data = [ { "id": "01", "close_approach_data": [ {"orbiting_body": "Earth", "approach_date": "1945-06-07"}, {"orbiting_body": "Earth", "approach_date": "1975-06-07"}, {"orbiting_body": "Mars", "approach_date": "1935-06-07"} ] }, { "id": "02", "close_approach_data": [ {"orbiting_body": "Earth", "approach_date": "1945-06-07"}, {"orbiting_body": "Earth", "approach_date": "1975-06-07"}, {"orbiting_body": "Mars", "approach_date": "1935-06-07"} ] } ]
你尝试的代码(存在的问题)
earthObjs =[] for element in data: for subel in element["close_approach_data"]: if ([subel][0]["orbiting_body"]=="Earth"): #then i would have to store the objects earthObjs.append([subel]) #here i am trying to find the object with the min 'approach_date' minEarth = min(dt.strptime(earthObjs["close_approach_date"],"%Y-%m-%d")) #then i would have to somehow place this as the only element of close_approach_data element["close_approach_data"] = json.loads(minEarth) #and clear the earthObjs list so it can be used for the next element earthObjs.clear()
你的代码主要有这几个问题:
- 没必要把
subel用[subel]包裹后存入列表,这会导致后续无法正确访问条目的属性 min()的用法错误:你需要基于日期值找到对应的条目,而不是直接对日期字符串取minjson.loads()完全用错了:我们操作的是Python字典对象,不是JSON字符串,不需要这个函数
修正后的代码
from datetime import datetime data = [ {"id": "01", "close_approach_data": [{"orbiting_body": "Earth", "approach_date": "1945-06-07"}, {"orbiting_body": "Earth", "approach_date": "1975-06-07"}, {"orbiting_body": "Mars", "approach_date": "1935-06-07"}]}, {"id": "02", "close_approach_data": [{"orbiting_body": "Earth", "approach_date": "1945-06-07"}, {"orbiting_body": "Earth", "approach_date": "1975-06-07"}, {"orbiting_body": "Mars", "approach_date": "1935-06-07"}]} ] for element in data: # 第一步:过滤出所有orbiting_body为Earth的条目 earth_entries = [entry for entry in element["close_approach_data"] if entry["orbiting_body"] == "Earth"] if earth_entries: # 第二步:找到approach_date最早的条目 # 用lambda表达式把日期字符串转成datetime对象作为比较的key earliest_earth_entry = min(earth_entries, key=lambda x: datetime.strptime(x["approach_date"], "%Y-%m-%d")) # 第三步:替换close_approach_data为这个单一条目 element["close_approach_data"] = earliest_earth_entry # 打印验证结果 import json print(json.dumps(data, indent=2))
代码解释
- 列表推导式过滤:用
[entry for entry in ... if ...]快速筛选出所有Earth相关的条目,比嵌套循环更简洁易读 - min()的key参数:这是核心!
key=lambda x: datetime.strptime(...)会把每个条目的日期字符串转成可比较的datetime对象,min()会自动返回日期最早的那个条目 - 直接替换值:我们直接把筛选后的单个条目赋值给
close_approach_data,不需要额外的转换操作,因为操作的就是Python原生的字典对象
运行这段代码后,你会得到符合需求的结果:
[ { "id": "01", "close_approach_data": { "orbiting_body": "Earth", "approach_date": "1945-06-07" } }, { "id": "02", "close_approach_data": { "orbiting_body": "Earth", "approach_date": "1945-06-07" } } ]
内容的提问来源于stack exchange,提问作者Andy96
相关产品推荐
相关产品推荐

