Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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搜索文件返回[]_Python_Json_Python 3.x - Fatal编程技术网

Python搜索文件返回[]

Python搜索文件返回[],python,json,python-3.x,Python,Json,Python 3.x,我试图在JSON文件中搜索用户名,但它只是返回[],而不是tom123 JSON文件内容: [{"id":"001788fffe48cbdb","username":"tom123"}] 代码: f是一个类似迭代器的文件对象,这意味着当您对其进行迭代时,您已经使用了它,并且不能再次使用它。在这种情况下,您首先在下面的行中消费它: print(f.read()) 对于加载json文件,还应使用json.load()函数。然后,您可以在阅读后保留内容,然后搜索保留的内容: with open("

我试图在JSON文件中搜索用户名,但它只是返回[],而不是tom123

JSON文件内容:

[{"id":"001788fffe48cbdb","username":"tom123"}]
代码:


f
是一个类似迭代器的文件对象,这意味着当您对其进行迭代时,您已经使用了它,并且不能再次使用它。在这种情况下,您首先在下面的行中消费它:

print(f.read())
对于加载json文件,还应使用
json.load()
函数。然后,您可以在阅读后保留内容,然后搜索保留的内容:

with open("first.json") as f
    content = json.load(f)
    username = [index["username"] for index in content]
    print(username)
此外,作为一种基于函数的方法,您可以使用
操作符.itemgetter
map()
来获得包含所有用户名的迭代器(在内存使用方面更优化):


f
是一个类似迭代器的文件对象,这意味着当您对其进行迭代时,您已经使用了它,并且不能再次使用它。在这种情况下,您首先在下面的行中消费它:

print(f.read())
对于加载json文件,还应使用
json.load()
函数。然后,您可以在阅读后保留内容,然后搜索保留的内容:

with open("first.json") as f
    content = json.load(f)
    username = [index["username"] for index in content]
    print(username)
此外,作为一种基于函数的方法,您可以使用
操作符.itemgetter
map()
来获得包含所有用户名的迭代器(在内存使用方面更优化):


也许像这样,你想解析json,这样你就可以像使用dict一样使用它

import json
import re
import requests

f = open("first.json", "r+")
data = json.loads(f.read())
username = [index["username"] for index in data]
print(username)
f.close()

也许像这样,你想解析json,这样你就可以像使用dict一样使用它

import json
import re
import requests

f = open("first.json", "r+")
data = json.loads(f.read())
username = [index["username"] for index in data]
print(username)
f.close()