여러 JSON 개체를 가진 JSON 파일 로드 및 구문 분석
Python에서 JSON 파일을 로드하여 해석하려고 합니다.하지만 파일을 로드하는 데 어려움을 겪고 있습니다.
import json
json_data = open('file')
data = json.load(json_data)
수율:
ValueError: Extra data: line 2 column 1 - line 225116 column 1 (char 232 - 160128774)
Python 문서에서 JSON 인코더와 디코더를 살펴보았습니다만, 이 보기 흉한 문서를 읽는 것은 매우 실망스러운 일입니다.
처음 몇 줄(랜덤화된 엔트리로 익명화):
{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
JSON Lines 형식의 텍스트 파일이 있습니다.파일을 한 줄씩 해석해야 합니다.
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
각 행에는 유효한 JSON이 포함되어 있지만 상위 수준 목록이나 개체 정의가 없기 때문에 전체적으로 유효한 JSON 값이 아닙니다.
파일에는 행당 JSON이 포함되어 있기 때문에 한 번에 모든 것을 해석하거나 스트리밍 JSON 파서를 계산하는 번거로움이 없어집니다.이제 다음 행으로 넘어가기 전에 각 행을 개별적으로 처리하도록 선택할 수 있으므로 프로세스에서 메모리를 절약할 수 있습니다.파일이 너무 크면 각 결과를 하나의 목록에 추가한 다음 모든 작업을 처리하고 싶지 않을 수 있습니다.
구분자가 구분된 개별 JSON 개체가 포함된 파일이 있는 경우 'json' 모듈을 사용하여 한 번에 하나의 JSON 개체를 읽으려면 어떻게 해야 합니까?버퍼링된 메서드를 사용하여 개별 개체를 구문 분석합니다.
사용하고 있는 경우pandas
로딩에 관심이 있을 것입니다.json
데이터 프레임으로서 다음의 파일을 사용할 수 있습니다.
import pandas as pd
df = pd.read_json('file.json', lines=True)
이를 json 배열로 변환하려면 다음을 사용합니다.
df.to_json('new_file.json')
이 질문에 부딪히는 사람들을 위해: 비단뱀jsonlines
라이브러리(이 질문보다 젊은 버전)는 한 줄에 하나의 json 문서가 있는 파일을 우아하게 처리합니다.https://jsonlines.readthedocs.io/ 를 참조해 주세요.
그것은 형식이 잘못되어 있다.한 줄에 하나의 JSON 개체가 있지만 이러한 개체가 더 큰 데이터 구조(배열)에 포함되지 않습니다.포맷을 다시 해야 합니다.[
으로 끝나다]
각 행 끝에 쉼표를 붙이거나 한 줄씩 별도의 사전으로 구문 분석합니다.
@arunppsg의 답변에 대한 추가 기능. 단, 디렉토리 내의 다수의 파일을 처리하기 위한 멀티프로세싱 기능.
import numpy as np
import pandas as pd
import json
import os
import multiprocessing as mp
import time
directory = 'your_directory'
def read_json(json_files):
df = pd.DataFrame()
for j in json_files:
with open(os.path.join(directory, j)) as f:
df = df.append(pd.read_json(f, lines=True)) # if there's multiple lines in the json file, flag lines to true, false otherwise.
return df
def parallelize_json(json_files, func):
json_files_split = np.array_split(json_files, 10)
pool = mp.Pool(mp.cpu_count())
df = pd.concat(pool.map(func, json_files_split))
pool.close()
pool.join()
return df
# start the timer
start = time.time()
# read all json files in parallel
df = parallelize_json(json_files, read_json)
# end the timer
end = time.time()
# print the time taken to read all json files
print(end - start)
언급URL : https://stackoverflow.com/questions/12451431/loading-and-parsing-a-json-file-with-multiple-json-objects
'programing' 카테고리의 다른 글
모든 Axios 요청에 대한 Authorization 헤더 첨부 (0) | 2023.04.02 |
---|---|
angularjs 앱에서 안전한(!) 인증 시스템을 얻는 방법 (0) | 2023.04.02 |
스프링 부트: 여러 SLF4J 바인딩 (0) | 2023.04.02 |
JSX React HTML5 입력 슬라이더가 작동하지 않음 (0) | 2023.04.02 |
왜 TypeScript의 'instanceof'에서 "Foo'는 유형만을 나타낼 뿐 여기서 값으로 사용되고 있습니다."라는 오류가 표시되는가? (0) | 2023.04.02 |