2015-05-29 32 views
10

Tôi muốn biết cách đọc một số tệp json từ một thư mục (không chỉ định tên tệp, chỉ là chúng là tệp json).Python: Đọc nhiều tệp json từ một thư mục

Ngoài ra, bạn có thể biến chúng thành một dữ liệu pandas DataFrame?

Bạn có thể cho tôi ví dụ cơ bản không?

Trả lời

13

Một lựa chọn được danh sách tất cả các file trong một thư mục với os.listdir và sau đó tìm kiếm chỉ những kết thúc bằng '.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'] 

Bây giờ bạn có thể sử dụng gấu trúc DataFrame.from_dict để đọc trong json (một cuốn từ điển python vào thời điểm này) cho một dataframe gấu trúc:

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

Prints:

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

Trong trường hợp này tôi đã nối thêm một số jsons vào danh sách many_jsons. Các json đầu tiên trong danh sách của tôi thực sự là một geojson với một số dữ liệu địa lý về Montreal. Tôi đã quen thuộc với nội dung nên tôi đã in ra 'hình học' mang lại cho tôi những lon/lat của Montreal.

Các mã sau đây tóm tắt tất cả mọi thứ trên:

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's look at it 
print(jsons_data) 

cho tôi bản in này:

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

Có thể hữu ích để biết rằng đối với mã này tôi có hai geojsons trong một tên thư mục ' json '. Mỗi json có cấu trúc sau:

{"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"} 
+0

Thực sự hữu ích. Thay vì in ý tưởng của tôi là để lưu tất cả chúng vào một khung dữ liệu gấu trúc, nên những gì sẽ là mã chính xác? tạo một khung dữ liệu trống và bắt đầu thêm hàng vào nó? Cảm ơn @Scott cho câu trả lời chi tiết này! – donpresente

+1

@donpresente Câu hỏi hay. Tôi sẽ đăng chỉnh sửa để giải quyết cách lấy một số dữ liệu mong muốn từ một json và sau đó đẩy dữ liệu này vào một DataFrame gấu trúc, theo hàng. – Scott

+1

@donpresente đã làm mã dưới ** EDIT ** giúp bạn? – Scott

1

Để đọc các tập tin 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)) 
+0

Nội dung.append đang tạo từ điển thêm tất cả các tệp json đã đọc vào trong đó? Cảm ơn @Saravana! – donpresente

+1

'contents.append' thêm một phần tử vào danh sách' nội dung'. –

+0

Sẽ có dấu phẩy sau "* .json ')" –

6

lặp lại một (phẳng) thư mục dễ dàng với mô-đun glob

from glob import glob 

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

Đối với đọc JSON trực tiếp vào pandas, xem here.

+0

Liên kết trực tiếp https://hayd.github.io/2013/pandas-json –

Các vấn đề liên quan