【发布时间】:2021-05-12 08:02:54
【问题描述】:
我是 Python(和 JSON)的新手,因此很抱歉你很明显。
我使用以下代码从 API 中提取一些数据
import requests
import json
headers = {'Content-Type': 'application/json', 'accept-encoding':'identity'}
api_url = api_url_base+api_token+api_request #variables removed for security
response = requests.get(api_url, headers=headers)
data=response.json()
keys=data.keys
if response.status_code == 200:
print(data["message"], "saving to file...")
print("Found the following keys:")
print(keys)
with open('vulns.json', 'w') as outfile:
json.dump(response.content.decode('utf-8'),outfile)
print("File Saved.")
else:
print('The site returned a', response.status_code, 'error')
这行得通,我得到了一些返回的数据,我可以写文件了。
我正在尝试将返回的内容从短格式更改为长格式并检查它的工作我需要查看密钥,我试图使用书面文件离线执行此操作(作为从文件中读取 JSON 的练习) .
我写了这几行(取自这个网站https://www.kite.com/python/answers/how-to-print-the-keys-of-a-dictionary-in-python)
导入 json
使用 open('vulns.json') 作为 json_file: 数据=json.load(json_file)
打印(数据) 键=列表(data.keys()) 打印(键)
不幸的是,每当我运行它时,它都会返回此错误
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(keys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'keys' is not defined
>>> & C:/Users/xxxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
File "<stdin>", line 1
& C:/Users/xxxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
^
SyntaxError: invalid syntax
>>> exit()
PS C:\Users\xxxx\Documents\scripts\Python> & C:/Users/xxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
Traceback (most recent call last):
File "c:\Temp\read-vulnfile.py", line 6, in <module>
keys=list(data.keys)
AttributeError: 'str' object has no attribute 'keys'
Print(data) 命令返回类似于 JSON 的内容,这是开头行:
{"count": 1000, "message": "发现漏洞:1000", "data": [{"...
我无法显示它的敏感内容。
- 为什么要查看 str 对象而不是字典?
- 请问如何将 JSON 读回字典?
【问题讨论】:
-
就在调用
data.keys之前输入print(data)。它说什么? -
另外,如果那是一个字典,你应该使用
data.keys()。 -
将 list(data,keys) 更改为 list(data.keys()) 已删除未定义的错误重新键,但它仍然指 str 没有属性键
Traceback (most recent call last): File "c:\Temp\read-vulnfile.py", line 7, in <module> keys=list(data.keys()) AttributeError: 'str' object has no attribute 'keys'- I'已通过更改为 list(data.keys()) 修改了问题,并尽可能多地添加了文件的输出。它很大而且很敏感。
标签: json python-3.x