如何读取 python 中的 json 对象

how to read json object in python

我有 json 个名为“panamaleaks50k.json”的文件。我想从 json 文件中获取 ['text'] 字段,但它显示以下错误

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'] 字段?

如果您的输入是类文件对象(例如 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'])

...输出为 success.

您应该将文件 内容(即字符串)传递给 json.loads(),而不是文件对象本身。试试这个:

with open(file_path) as f:
    data = json.loads(f.read())
    print(data[0]['text'])

还有一个 json.load() 函数,它接受一个文件对象并在后台为您完成 f.read() 部分。