Bil*_*utt 10 python json filereader
我有一个名为"panamaleaks50k.json"的json文件.我想从json文件中获取['text']字段,但它显示我跟随错误
JSON对象必须是str,bytes或bytearray,而不是'TextIOWrapper'
这是我的代码
with open('C:/Users/bilal butt/Desktop/PanamalEakJson.json','r') as lst:
b = json.loads(lst)
print(b['text'])
Run Code Online (Sandbox Code Playgroud)
我的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"
}
]
Run Code Online (Sandbox Code Playgroud)
我如何阅读所有['text']和单个['text']字段?
Eug*_*ash 23
您应该将文件内容(即字符串)传递给json.loads()
文件对象本身.试试这个:
with open(file_path) as f:
data = json.loads(f.read())
print(data[0]['text'])
Run Code Online (Sandbox Code Playgroud)
还有json.load()
一个接受文件对象的功能,并f.read()
为您完成部分工作.
如果您的输入是类似文件的对象(例如TextIOWrapper),请使用json.load()
,而不要使用json.loads()
。
给出以下完整的复制器:
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'])
Run Code Online (Sandbox Code Playgroud)
...输出success
。
归档时间: |
|
查看次数: |
34782 次 |
最近记录: |