Python 加载JSON文件以读取和选择数据
我有一个加载到python中的json文件。我想从文件中提取一个关键词(非常大),比如国家排名或从互联网上获取的信息中的评论。我试过了Python 加载JSON文件以读取和选择数据,python,json,Python,Json,我有一个加载到python中的json文件。我想从文件中提取一个关键词(非常大),比如国家排名或从互联网上获取的信息中的评论。我试过了 json.load('filename.json') 但我得到了一个错误: AttributeError: 'str' object has no attribute 'read.' 我做错了什么 另外,如果json文件很大,我如何选择它的一部分呢?我认为您需要打开该文件,然后像这样将其传递给json加载 import json from pprint i
json.load('filename.json')
但我得到了一个错误:
AttributeError: 'str' object has no attribute 'read.'
我做错了什么
另外,如果json文件很大,我如何选择它的一部分呢?我认为您需要打开该文件,然后像这样将其传递给json加载
import json
from pprint import pprint
with open('filename.json') as data:
output = json.load(data)
pprint(output)
我认为您需要打开该文件,然后像这样将其传递给json加载
import json
from pprint import pprint
with open('filename.json') as data:
output = json.load(data)
pprint(output)
请尝试以下操作:
import json
json_data_file = open("json_file_path", 'r').read() # r for reading the file
json_data = json.loads(json_data_file)
使用以下键访问数据:
json_data['key']
请尝试以下操作:
import json
json_data_file = open("json_file_path", 'r').read() # r for reading the file
json_data = json.loads(json_data_file)
使用以下键访问数据:
json_data['key']
json.load()
with open('filename.json') as datafile:
data = json.load(datafile)
例如,如果您的json数据如下所示:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
要访问部分数据,请使用:
data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]
该代码可在此SO答案中找到:
json.load()
在打开文件后需要该文件句柄:
with open('filename.json') as datafile:
data = json.load(datafile)
例如,如果您的json数据如下所示:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
要访问部分数据,请使用:
data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]
该代码可在此SO答案中找到:
您是否尝试了json.loads('filename.json')
?您正在读取字符串您是否尝试了json.loads('filename.json')
?当我使用这段代码时,我喜欢它现在执行的方式,错误是:“从None中提升JSONDecodeError(“期望值”,s,err.value)JSONDecodeError:Expecting value”,然后我尝试使用json.loads()并获取“TypeError:JSON对象必须是str,而不是'TextIOWrapper'”你确定文件filename.JSON中包含数据吗?当我使用这段代码时,我得到了“AttributeError:'str'对象没有属性'read'”,我喜欢它现在的处理方式。错误是:“raise JSONDecodeError”(“预期值”,s,err.value)from None JSONDecodeError:期望值“然后我尝试使用json.loads()并获取”TypeError:json对象必须是str,而不是“TextIOWrapper”?您确定文件filename.json中包含数据吗?