如何在python

时间:2017-12-17 16:30:35

标签: python json filereader

我的json文件名为" panamaleaks50k.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'])

我的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"
 }
]

我如何阅读所有['文字']和单个['文字']字段?

2 个答案:

答案 0 :(得分:14)

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

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

还有json.load()函数,它接受一个文件对象并为你做f.read()部分。

答案 1 :(得分:6)

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