Подтвердить что ты не робот

Python: прочитайте несколько json файлов из папки

Я хотел бы знать, как читать несколько файлов json из одной папки (без указания имен файлов, просто они являются json файлами).

Кроме того, можно превратить их в pandas DataFrame?

Можете ли вы дать мне базовый пример?

4b9b3361

Ответ 1

Один из вариантов - перечислить все файлы в каталоге с помощью os.listdir, а затем найти только те, которые заканчиваются на .json:

import os, json
import pandas as pd

path_to_json = 'somedir/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files)  # for me this prints ['foo.json']

Теперь вы можете использовать pandas DataFrame.from_dict для чтения в json (словарь python в данный момент) в pandas dataframe:

montreal_json = pd.DataFrame.from_dict(many_jsons[0])
print montreal_json['features'][0]['geometry']

Печать:

{u'type': u'Point', u'coordinates': [-73.6051013, 45.5115944]}

В этом случае я добавил несколько jsons в список many_jsons. Первый JSON в моем списке на самом деле геойсон с некоторыми геоданными в Монреале. Я уже знаком с содержанием, поэтому распечатываю "геометрию", которая дает мне долготу и широту Монреаля.

Следующий код подводит итог всему вышесказанному:

import os, json
import pandas as pd

# this finds our json files
path_to_json = 'json/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

# here I define my pandas Dataframe with the columns I want to get from the json
jsons_data = pd.DataFrame(columns=['country', 'city', 'long/lat'])

# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)

        # here you need to know the layout of your json and each json has to have
        # the same structure (obviously not the structure I have here)
        country = json_text['features'][0]['properties']['country']
        city = json_text['features'][0]['properties']['name']
        lonlat = json_text['features'][0]['geometry']['coordinates']
        # here I push a list of data into a pandas DataFrame at row given by 'index'
        jsons_data.loc[index] = [country, city, lonlat]

# now that we have the pertinent json data in our DataFrame let look at it
print(jsons_data)

для меня это печатает:

  country           city                   long/lat
0  Canada  Montreal city  [-73.6051013, 45.5115944]
1  Canada        Toronto  [-79.3849008, 43.6529206]

Может быть полезно знать, что для этого кода у меня было два геоджона в каталоге с именем "json". Каждый JSON имел следующую структуру:

{"features":
[{"properties":
{"osm_key":"boundary","extent":
[-73.9729016,45.7047897,-73.4734865,45.4100756],
"name":"Montreal city","state":"Quebec","osm_id":1634158,
"osm_type":"R","osm_value":"administrative","country":"Canada"},
"type":"Feature","geometry":
{"type":"Point","coordinates":
[-73.6051013,45.5115944]}}],
"type":"FeatureCollection"}

Ответ 2

Итерирование (плоского) каталога легко с помощью glob module

from glob import glob

for f_name in glob('foo/*.json'):
    ...

Что касается чтения JSON непосредственно в pandas, см. здесь.

Ответ 3

Чтобы прочитать json файлы,

import os
import glob

contents = []
json_dir_name = "/path/to/json/dir"

json_pattern = os.path.join(json_dir_name,'*.json'
file_list = glob.glob(json_pattern)
for file in file_list:
  contents.append(read(file))