Hướng dẫn how do i read all json files in a directory in python? - làm cách nào để đọc tất cả các tệp json trong một thư mục trong python?

Một tùy chọn là liệt kê tất cả các tệp trong một thư mục với Os.ListDir và sau đó chỉ tìm thấy các tệp kết thúc trong '.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 (từ điển Python tại thời điểm này) đến DataFrame của Pandas:

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 đã thêm một số Jsons vào danh sách many_jsons. 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 GEO trên Montreal. Tôi đã quen thuộc với nội dung rồi nên tôi in ra 'hình học' mang lại cho tôi Lon/Lat của Montreal.

Mã sau đây tổng hợp 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)

Đối với 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 khi 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"}

So sánh dữ liệu từ nhiều tệp JSON có thể trở nên không phù hợp - trừ khi bạn tận dụng Python để cung cấp cho bạn dữ liệu bạn cần.

Tôi thường theo dõi các số liệu tốc độ trang chính bằng cách kiểm tra các trang web bằng WebPagetest hoặc Google Ngọn hải đăng bằng các công cụ CLI hoặc Node của họ.Tôi lưu kết quả kiểm tra dưới dạng JSON, điều này tốt để xem các ảnh chụp nhanh cá nhân sau đó.Nhưng tôi thường kết thúc với các thư mục chứa đầy dữ liệu không thể được phân tích thủ công:

working_directory
└───data
    ├───export1.json
    ├───export2.json
    ├───export3.json
    ├───...

Ví dụ, làm thế nào để so sánh các thay đổi trong các số liệu đó theo thời gian?Hoặc làm thế nào để tìm kiếm một đỉnh trong dữ liệu?

Kịch bản Python 3 tiện dụng sau đây rất hữu ích cho việc sàng lọc thông qua một thư mục đầy các tệp JSON và xuất các giá trị cụ thể sang CSV để phân tích ad-hoc.Nó chỉ sử dụng các mô-đun Python tích hợp.Tôi chỉ bỏ nó vào thư mục làm việc của mình và chạy nó qua dòng lệnh với

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

json-to-csv-exporter.py

#!/usr/bin/env python3

# Place this Python script in your working directory when you have JSON files in a subdirectory.
# To run the script via command line: "python3 json-to-csv-exporter.py"

import json
import glob
from datetime import datetime
import csv

# Place your JSON data in a directory named 'data/'
src = "data/"

date = datetime.now()
data = []

# Change the glob if you want to only look through files with specific names
files = glob.glob('data/*', recursive=True)

# Loop through files

for single_file in files:
with open(single_file, 'r') as f:

# Use 'try-except' to skip files that may be missing data
try:
json_file = json.load(f)
data.append([
json_file['requestedUrl'],
json_file['fetchTime'],
json_file['categories']['performance']['score'],
json_file['audits']['largest-contentful-paint']['numericValue'],
json_file['audits']['speed-index']['numericValue'],
json_file['audits']['max-potential-fid']['numericValue'],
json_file['audits']['cumulative-layout-shift']['numericValue'],
json_file['audits']['first-cpu-idle']['numericValue'],
json_file['audits']['total-byte-weight']['numericValue']
])
except KeyError:
print(f'Skipping {single_file}')

# Sort the data
data.sort()

# Add headers
data.insert(0, ['Requested URL', 'Date', 'Performance Score', 'LCP', 'Speed Index', 'FID', 'CLS', 'CPU Idle', 'Total Byte Weight'])

# Export to CSV.
# Add the date to the file name to avoid overwriting it each time.
csv_filename = f'{str(date)}.csv'
with open(csv_filename, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)

print("Updated CSV")

Điều đó cung cấp cho bạn một CSV mà bạn có thể sử dụng để tạo biểu đồ hoặc phân tích cho nội dung trái tim của bạn.

________số 8