Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类型错误:'_io.TextIOWrapper';对象在读取JSON时不可订阅_Python_Json_Python 3.x - Fatal编程技术网

Python 类型错误:'_io.TextIOWrapper';对象在读取JSON时不可订阅

Python 类型错误:'_io.TextIOWrapper';对象在读取JSON时不可订阅,python,json,python-3.x,Python,Json,Python 3.x,下面是一个导致错误的json文件和代码片段的示例。我正在尝试使用postid搜索json文件以检索文章标题 谢谢 [ { "gy36v6": "A good boy at a Minneapolis protest today" }, { "gy7hpi": "Einstein lecturing at an HBCU" }, { "gyddyc": "Soldier ant \ud83d\udc1c"

下面是一个导致错误的json文件和代码片段的示例。我正在尝试使用postid搜索json文件以检索文章标题

谢谢

[
    {
        "gy36v6": "A good boy at a Minneapolis protest today"
    },
    {
        "gy7hpi": "Einstein lecturing at an HBCU"
    },
    {
        "gyddyc": "Soldier ant \ud83d\udc1c"
    },
    {
        "gyec4a": "It\u2019s not what I usually post but thought it was a cool cake I got."
    }
]

fileobj
只是一个文件对象;它不知道它包含JSON。使用将其转换为Python数据,例如:

import json

def post(postid):
    with open('used.json', 'r') as fileobj:
         data = json.load(fileobj)
    title = data[postid]
    return title

print(post(0))  # -> {'gy36v6': 'A good boy at a Minneapolis protest today'}

fileobj
只是一个文件对象;它不知道它包含JSON。使用将其转换为Python数据,例如:

import json

def post(postid):
    with open('used.json', 'r') as fileobj:
         data = json.load(fileobj)
    title = data[postid]
    return title

print(post(0))  # -> {'gy36v6': 'A good boy at a Minneapolis protest today'}

嗯,是的。您没有使用
json
库来反序列化输入。你不能只是打开一个文件,然后假设你可以把它的内容当作一个字典。您没有使用
json
库来反序列化输入。你不能仅仅打开一个文件,然后假设你可以把它的内容当作一个字典来对待。谢谢你!不幸的是,这立即导致“title=data[postid]”出现错误,表示“TypeError:列表索引必须是整数或片,而不是str”。您能给出的任何澄清都会非常有用。@Matt您的JSON是一个dict列表。你可能想。非常感谢你!不幸的是,这立即导致“title=data[postid]”出现错误,表示“TypeError:列表索引必须是整数或片,而不是str”。您能给出的任何澄清都会非常有用。@Matt您的JSON是一个dict列表。你可能想。
import json

def post(postid):
    with open('used.json', 'r') as fileobj:
         data = json.load(fileobj)
    title = data[postid]
    return title

print(post(0))  # -> {'gy36v6': 'A good boy at a Minneapolis protest today'}