将 json 转换为 python 中的数据帧

converting json to dataframe in python

我想将多个 JSON 文件转换为一个数据帧。

下面是 JSON 对象:

{'alerts': [{'affected_services': {'elevators': [],
                                   'services': [{'mode_name': 'Subway',
                                                 'route_id': 'Red',
                                              'route_name': 'Red''Line',
'route_type': '1',
'stop_id': '70061',
'stop_name': 'Alewife'},
{'mode_name': 'Subway',
'route_id': 'Red',
'route_name': 'Red ''Line',
'route_type': '1',
'stop_id': '70063',
'stop_name': 'Davis ''- ''Inbound'}]},
                         'alert_id': 176434,
                         'alert_lifecycle': 'Upcoming',
                         'cause': 'UNKNOWN_CAUSE',
                         'created_dt': '1491332705',
                         'description_text': 'Due to the Floating Slab '
                             'Project, buses will replaceRed ',
                         'effect': 'DETOUR',
                         'effect_name': 'Shuttle',
                         'effect_periods': [{'effect_end': '1493620200',
                         'effect_start': '1493454600'}],
                  'header_text': 'Buses will replace Red Line service',
                         'last_modified_dt': '1491332705',
                         'service_effect_text': 'Red Line shuttle',
                         'severity': 'Severe',
                    'short_header_text': 'Buses will replace Red Line ',
                    'timeframe_text': 'April 29-30',
'url': 'http://www.mbta.com/about_the_mbta/t_projects/default.asp?id=22956'}],
             'stop_id': 'place-alfcl',
             'stop_name': 'Alewife'}

下面是我试过的代码:

from pandas.io.json import json_normalize
import pandas as pd
import glob

json_file_path = path_stop +'*'
lambda_file = lambda json_file_path : glob.glob(json_file_path)

for json_file in lambda_file(json_file_path):
    with open(json_file) as json_data:
        result = json_normalize(json_data,'alerts',['affected_services',['elevators','services',['mode_name','route_id','stop_id','stop_name']],'alert_lifecycle','cause','created_dt','effect','effect_name','severity','timeframe_text'],'stop_id','stop_name')

print(result)

请有人帮助我。提前致谢!

如果您将 json 作为字符串,您可以通过调用

将其转换为 json 对象
temp = json.load(JSON_string)

那么你应该可以调用:

df = pd.read_json(temp)

然后你有你的数据框"df"

这段代码应该可以满足您的需求:

import pandas
import glob
json_files = glob.glob('*.json')
def merge_files(json_files):
    dfs = list()
    for json_file in json_files:
        df = pandas.read_json(json_file)
        dfs.append(df)
    df = pandas.concat(dfs)
    return df

df = merge_files(json_files)

但是,我要提醒您,您可能想要更多地处理输入数据,以便了解您正在构建的 DataFrame 的形状和内容。

以上回答有一定帮助。当您有复杂的列表和字典类型的结构时,我建议将请求的数据存储在 CSV 中,而不是以 JSON 格式存储数据。将数据转换成数据框会很容易。

我没有使用 JSON 文件制作数据框,而是使用 CSV 文件,然后转换为数据框。