如何在python中读取json对象 [英] how to read json object in python
本文介绍了如何在python中读取json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为"panamaleaks50k.json"的json文件.我想从json文件中获取['text']字段,但显示以下错误
i have json file named "panamaleaks50k.json" . I want to get ['text'] field from json file but it shows me following error
JSON对象必须是str,bytes或bytearray,而不是'TextIOWrapper'
the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'
这是我的代码
with open('C:/Users/bilal butt/Desktop/PanamalEakJson.json','r') as lst:
b = json.loads(lst)
print(b['text'])
我的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']字段?
how i can read all ['text'] and just single ['text'] field?
推荐答案
您应该将文件 contents (即字符串)传递给json.loads()
,而不是文件对象本身.试试这个:
You should pass the file contents (i.e. a string) to json.loads()
, not the file object itself. Try this:
with open(file_path) as f:
data = json.loads(f.read())
print(data[0]['text'])
还有 json.load()
函数,该函数接受文件对象,并在后台为您执行f.read()
部分.
这篇关于如何在python中读取json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文