Python의 JSON 파일에서 데이터 추출 [중복]

Nov 08 2020

안녕하세요 여러분! "스 트리머"에서 모든 이름을 가져와야하는데 어떻게 할 수 있을지 모르겠어요. 당신이 나를 도울 수있을 것입니다.

감사!

JSON 파일 :

    "streamers": [
        {},
        {
            "name": "One\n\n"
        },
        {
            "name": "Two\n\n"
        },
        {
            "name": "Three\n\n"
        }
    ]
}

답변

jojo_Berlin Nov 08 2020 at 01:51

좋아, 기본적으로 할 수있는 일 :

import json

names=[]
with open('data.txt') as json_file:
  dict=json.load(json_file)["streamers"]
  for tuple in dict:
    if "name" in tuple:
      names.append(tuple["name"]
print(names)
 

MelvinAbraham Nov 08 2020 at 01:49

모듈 의 load메소드를 사용할 수 있습니다 json. 이 함수는 파일 핸들러, 특히 JSON 파일을 수락 한 다음이를 코드에서 즉시 사용할 수있는 Python 사전 객체로 변환합니다.

다음 스 니펫을 참조 할 수 있습니다.

import json

f = open('path/to/file/file.json')      # Open the JSON file
dictionary = json.load(f)               # Parse the JSON file
f.close()                               # Close the JSON file

streamers = dictionary['streamers']
print(streamers)

산출


[
    {},
    {
        "name": "One\n\n"
    },
    {
        "name": "Two\n\n"
    },
    {
        "name": "Three\n\n"
    }
]
Gabip Nov 08 2020 at 02:00

시험:

import json

with open('path/to/file.json') as f:
    names = [x.get("name") for x in json.load(f)["streamers"] if x.get("name")]
    print(names)