티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
한 줄씩 파싱하는 것은 높은 점수를 받은 솔루션을, 데이터프레임으로 한번에 파싱하는 것은 가장 최근 달린 솔루션을 참고하세요.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Loading and parsing a JSON file with multiple JSON objects
여러 개의 JSON 객체를 포함하는 JSON 파일을 로드하고 파싱하기
문제 내용
I am trying to load and parse a JSON file in Python. But I'm stuck trying to load the file:
저는 파이썬에서 JSON 파일을 로드하고 파싱하려고 하는데 파일을 로드하는 데에 문제가 있습니다.
import json json_data = open('file') data = json.load(json_data)
Yields:
ValueError: Extra data: line 2 column 1 - line 225116 column 1 (char 232 - 160128774)
I looked at 18.2. json
— JSON encoder and decoder in the Python documentation, but it's pretty discouraging to read through this horrible-looking documentation.
저는 Python 문서의 18.2절인 "json — JSON 인코더 및 디코더"를 살펴봤지만, 이런 형편없이 보기 싫은 문서를 읽어내려가는 것은 꽤 어려웠습니다.
First few lines (anonymized with randomized entries):
처음 몇 줄(랜덤한 항목으로 익명화):
{"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"}
높은 점수를 받은 Solution
You have a JSON Lines format text file. You need to parse your file line by line:
JSON Lines 형식의 텍스트 파일이 있습니다. 파일을 한 줄씩 파싱해야 합니다.
import json data = [] with open('file') as f: for line in f: data.append(json.loads(line))
Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.
각 라인은 유효한 JSON 값을 포함하지만, 전체적으로는 상위 수준의 리스트나 객체 정의가 없기 때문에 유효한 JSON 값이 아닙니다.
Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.
파일의 각 줄이 JSON 형식인 경우, 한 번에 전체를 파싱하려고 하거나 스트리밍 JSON 파서를 구성하려고 하는 고생을 덜 수 있습니다. 이제 각 줄을 개별적으로 처리한 다음 다음으로 이동할 수 있으므로 메모리를 절약할 수 있습니다. 파일이 매우 큰 경우 모든 결과를 하나의 리스트에 추가한 다음 처리하지 않는 것이 좋습니다.
If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.
각 JSON 객체들 사이에 구분자(delimiter)가 있는 파일이 있다면, 'json' 모듈을 사용하여 버퍼 방식으로 각 객체를 파싱하여 개별적으로 읽어들이는 방법은 'How do I use the 'json' module to read in one JSON object at a time?'을 참고하세요.
가장 최근 달린 Solution
In case you are using pandas
and you will be interested in loading the json
file as a dataframe, you can use:
만약 pandas를 사용하고 json 파일을 데이터프레임으로 로드하려면 다음을 사용할 수 있습니다:
import pandas as pd df = pd.read_json('file.json', lines=True)
And to convert it into a json array, you can use:
그리고 이것을 json 배열로 변환하려면 다음을 사용할 수 있습니다:
df.to_json('new_file.json')
출처 : https://stackoverflow.com/questions/12451431/loading-and-parsing-a-json-file-with-multiple-json-objects
'개발 > 파이썬' 카테고리의 다른 글
CSV 파일 한 줄씩 작성하기 (0) | 2023.02.03 |
---|---|
.py 파일과 .pyc 파일의 차이점 (0) | 2023.02.03 |
리스트에서 포함 여부 체크하기 (0) | 2023.02.02 |
Python에서 파일 읽기 및 덮어쓰기 (0) | 2023.02.01 |
문자열 리스트에 특정 문자열이 있는지 확인하기 (0) | 2023.01.31 |