如何在python中读取json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47857154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:24:48  来源:igfitidea点击:

how to read json object in python

pythonjsonfilereader

提问by Bilal Butt

i have json file named "panamaleaks50k.json" . I want to get ['text'] field from json file but it shows me following error

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

the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

JSON 对象必须是 str、bytes 或 bytearray,而不是“TextIOWrapper”

this is my code

这是我的代码

with open('C:/Users/bilal butt/Desktop/PanamalEakJson.json','r') as lst:
    b = json.loads(lst)
    print(b['text'])

my json file look

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

how i can read all ['text'] and just single ['text'] field?

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

回答by Eugene Yarmash

You should pass the file contents(i.e. a string) to json.loads(), not the file object itself. Try this:

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

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

There's also the json.load()function which accepts a file object and does the f.read()part for you under the hood.

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

回答by Charles Duffy

Use json.load(), not json.loads(), if your input is a file-like object (such as a TextIOWrapper).

如果您的输入是类似文件的对象(例如 TextIOWrapper),请使用json.load(),而不是json.loads()

Given the following complete reproducer:

给定以下完整的复制器:

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'])

...the output is success.

...输出是success