2017-02-03 82 views
0

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

JSON文件的内容:

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

代码:

import json 
import re 
import requests 

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

回答

1

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) 

另外,作为一个基于功能性的方法,你可以使用operator.itemgettermap()为了得到一个迭代器包含了所有的用户名(这是更优化:然后你就可以阅读,然后搜索虽然保存下来的内容后保存的内容在内存使用方面):

from operator import itemgetter 
with open("first.json") as f 
     content = json.load(f) 
     usernames = map(itemgetter("username"), content) 
+0

谢谢,现在作品:) –

1

也许这样的事情要解析JSON,所以你可以使用它像一个字典

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() 
+0

谢谢,现在作品:) –