반응형
python에서 json 객체를 읽는 방법
panamaleaks50k.json이라는 json 파일을 가지고 있습니다.json 파일에서 ['text']필드를 가져오고 싶은데 다음 오류가 나타납니다.
JSON 개체는 '텍스트'가 아니라 str, 바이트 또는 byearray여야 합니다.IOWrapper'
이건 내 코드야
with open('C:/Users/bilal butt/Desktop/PanamalEakJson.json','r') as lst:
b = json.loads(lst)
print(b['text'])
my json 파일 룩
[
{
"fullname": "Mohammad Fayyaz",
"id": "885800668862263296",
"likes": "0",
"replies": "0",
"retweets": "0",
"text": "Love of NS has been shown in PanamaLeaks scandal verified by JIT...",
"timestamp": "2017-07-14T09:58:31",
"url": "/mohammadfayyaz/status/885800668862263296",
"user": "mohammadfayyaz"
},
{
"fullname": "TeamPakistanPTI \u00ae",
"id": "885800910357749761",
"likes": "0",
"replies": "0",
"retweets": "0",
"text": "RT ArsalanISF: #PanamaLeaks is just a start. U won't believe whr...",
"timestamp": "2017-07-14T09:59:29",
"url": "/PtiTeampakistan/status/885800910357749761",
"user": "PtiTeampakistan"
}
]
['text']필드와 ['text']필드를 모두 읽을 수 있는 방법은 무엇입니까?
파일 객체 자체가 아닌 파일 내용(예: 문자열)을 에 전달해야 합니다.이것을 시험해 보세요.
with open(file_path) as f:
data = json.loads(f.read())
print(data[0]['text'])
파일 오브젝트를 받아들여 파일 오브젝트를 실행하는 기능도 있습니다.f.read()당신을 위해 후드 아래에서 헤어집니다.
사용하다json.load(),것은 아니다.json.loads()입력이 파일과 같은 오브젝트(텍스트 등)인 경우IOWrapper)
다음과 같은 완전한 리플리케이터가 있는 경우:
import json, tempfile
with tempfile.NamedTemporaryFile() as f:
f.write(b'{"text": "success"}'); f.flush()
with open(f.name,'r') as lst:
b = json.load(lst)
print(b['text'])
...출력은success.
언급URL : https://stackoverflow.com/questions/47857154/how-to-read-json-object-in-python
반응형
'programing' 카테고리의 다른 글
| 프로젝터 - 서로 다른 브라우저에서 여러 테스트를 병렬로 실행합니다. (0) | 2023.03.04 |
|---|---|
| Electron과 함께 리액트 라우터를 사용하는 방법 (0) | 2023.03.04 |
| 스프링 프레임워크에서의 의존성 주입 및 제어 반전이란 무엇입니까? (0) | 2023.03.04 |
| 현재 및 시간에 대한 Firebase TIMESTAMP (0) | 2023.03.04 |
| Angular CLI를 사용하여 특정 폴더에 컴포넌트를 생성하는 방법 (0) | 2023.03.04 |