codememo

JSONL 파일을 JSON 개체로 로드하는 중

tipmemo 2023. 3. 9. 22:05
반응형

JSONL 파일을 JSON 개체로 로드하는 중

Python에서 JSONL 파일을 JSON 오브젝트로 로드하고 싶습니다.그렇게 하는 쉬운 방법이 있을까요?

저 같은 초보자를 위한 파일 조작을 포함한 전체 단계

를 가지고 있다고 가정합니다..jsonl다음과 같은 파일:

{"reviewerID": "A2IBPI20UZIR0U", "asin": "1384719342", "reviewerName": "cassandra tu \"Yeah, well, that's just like, u...", "helpful": [0, 0], "reviewText": "Not much to write about here, but it does exactly what it's supposed to. filters out the pop sounds. now my recordings are much more crisp. it is one of the lowest prices pop filters on amazon so might as well buy it, they honestly work the same despite their pricing,", "overall": 5.0, "summary": "good", "unixReviewTime": 1393545600, "reviewTime": "02 28, 2014"}
{"reviewerID": "A14VAT5EAX3D9S", "asin": "1384719342", "reviewerName": "Jake", "helpful": [13, 14], "reviewText": "The product does exactly as it should and is quite affordable.I did not realized it was double screened until it arrived, so it was even better than I had expected.As an added bonus, one of the screens carries a small hint of the smell of an old grape candy I used to buy, so for reminiscent's sake, I cannot stop putting the pop filter next to my nose and smelling it after recording. :DIf you needed a pop filter, this will work just as well as the expensive ones, and it may even come with a pleasing aroma like mine did!Buy this product! :]", "overall": 5.0, "summary": "Jake", "unixReviewTime": 1363392000, "reviewTime": "03 16, 2013"}

이 코드는 동작합니다.

import json

with open('./data/my_filename.jsonl', 'r') as json_file:
    json_list = list(json_file)

for json_str in json_list:
    result = json.loads(json_str)
    print(f"result: {result}")
    print(isinstance(result, dict))

대해서.jsonl파일:
http://jsonlines.org/

파라미터 라인을 True로 설정하면 문제가 해결됩니다.

import pandas as pd    
jsonObj = pd.read_json(path_or_buf=file_path, lines=True)

스플릿 라인이 이 문제에 대응하고 있기 때문에, 일반적으로 이하의 코드가 유효합니다.

import json

result = [json.loads(jline) for jline in jsonl_content.splitlines()]

이것이 응답 객체일 경우 결과는 다음과 같습니다.

result = [json.loads(jline) for jline in response.read().splitlines()]

사용하지 않고 빠르고 쉬운 네이티브 솔루션split()기능:

import json
with open('/path/to/file.jsonl') as f:
    data = [json.loads(line) for line in f]

키를 추가할 수 있지만 이 방법은 작동합니다.예를 들어, 각 행의 형식은 다음과 같습니다.기본적으로 j_line은 사전이며 사전 접근 방법처럼 각 요소에 액세스합니다.중첩된 개체에 액세스하는 공유도 있습니다.

{"key1":"value", "key2":{"prop_1": "value"}

with open("foo.jsonl") as f1:
   for line in f1:
      j_line=json.loads(line)
      key_1=j_line['key1'] 
      prop_1=j_line['key2']['prop_2]

언급URL : https://stackoverflow.com/questions/50475635/loading-jsonl-file-as-json-objects

반응형