如何用Python/Pandas将JSON转为指定行列格式?当前代码无输出
JSON转Pandas结构化表格解决方案
问题排查与修复
你的代码无输出的核心原因是变量引用错误,以及未做键存在性校验导致循环提前中断。具体问题:
- 计算
days_until_departure时错误使用未定义的departure变量,应改为schedule["departure"] - 直接通过键名取值(如
leg["carrier"]["operating"]),若JSON中某字段缺失会触发KeyError导致循环终止 - 未提取你要求的ID字段(原问题要求每个ID作为一行)
修复后的完整代码
import pandas as pd from datetime import datetime # 假设df_json已完成JSON加载 data = [] columns = [ "ID", "Departure City", "Departure Date", "Departure Time", "Arrival Location", "Arrival Date", "Arrival Time", "Flight Duration", "Operating Carrier", "Aircraft Type", "Cabin Class", "Fare Class", "Price", "Days Until Departure" ] # 先预取全局结构,避免重复嵌套取值 itinerary_groups = df_json.get("groupedItineraryResponse", {}).get("itineraryGroups", []) schedule_descs = df_json.get("groupedItineraryResponse", {}).get("scheduleDescs", []) for group in itinerary_groups: itineraries = group.get("itineraries", []) for itinerary in itineraries: # 提取ID字段,满足每行对应一个ID的要求 itinerary_id = itinerary.get("id") if not itinerary_id: continue legs = itinerary.get("legs", []) if not legs: continue leg = legs[0] schedules = leg.get("schedules", []) if not schedules: continue schedule_ref = schedules[0].get("ref") # 校验索引合法性,避免越界报错 if not schedule_ref or schedule_ref - 1 >= len(schedule_descs): continue schedule = schedule_descs[schedule_ref - 1] # 用.get()层级取值,避免字段缺失触发KeyError departure_info = schedule.get("departure", {}) departure_city = departure_info.get("city") departure_time_str = departure_info.get("time") arrival_info = schedule.get("arrival", {}) arrival_location = arrival_info.get("city") arrival_time_str = arrival_info.get("time") # 拆分日期与时间,兼容缺失场景 departure_date = departure_time_str.split("T")[0] if departure_time_str else None departure_time = departure_time_str.split("T")[1] if departure_time_str else None arrival_date = arrival_time_str.split("T")[0] if arrival_time_str else None arrival_time = arrival_time_str.split("T")[1] if arrival_time_str else None flight_duration = leg.get("elapsedTime") carrier_info = leg.get("carrier", {}) operating_carrier = carrier_info.get("operating") equipment_info = carrier_info.get("equipment", {}) aircraft_type = equipment_info.get("code") passenger_info = itinerary.get("passengerInfoList", [{}])[0] fare_component = passenger_info.get("fareComponents", [{}])[0] cabin_class = fare_component.get("cabinCode") fare_class = fare_component.get("fareBasisCode") total_fare = itinerary.get("totalFare", {}) price = total_fare.get("totalPrice") # 计算出发前天数,捕获日期格式异常 days_until_departure = None if departure_date: try: current_date = datetime.now().date() departure_date_dt = datetime.strptime(departure_date, "%Y-%m-%d").date() days_until_departure = (departure_date_dt - current_date).days except ValueError: pass # 仅保留核心字段完整的数据行 if departure_city and arrival_location and price: data.append([ itinerary_id, departure_city, departure_date, departure_time, arrival_location, arrival_date, arrival_time, flight_duration, operating_carrier, aircraft_type, cabin_class, fare_class, price, days_until_departure ]) df = pd.DataFrame(data, columns=columns) # 查看输出结果 print(df.head())
关键改进说明
- 全程使用
.get()方法取值,彻底避免字段缺失导致的程序崩溃 - 新增ID字段提取,完全匹配你“每个ID作为一行”的需求
- 增加日期格式异常捕获,防止无效日期字符串中断循环
- 加入核心字段存在性判断,过滤空数据行,保证结果有效性
内容的提问来源于stack exchange,提问作者c200402
相关产品推荐
相关产品推荐

