【问题标题】:reading JSON from file and extract the keys returns attribute str has no keys从文件中读取 JSON 并提取键返回属性 str 没有键
【发布时间】: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": [{"...

我无法显示它的敏感内容。

  1. 为什么要查看 str 对象而不是字典?
  2. 请问如何将 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 &lt;module&gt; keys=list(data.keys()) AttributeError: 'str' object has no attribute 'keys' - I'已通过更改为 list(data.keys()) 修改了问题,并尽可能多地添加了文件的输出。它很大而且很敏感。

标签: json python-3.x


【解决方案1】:

您只需将该内容作为字符串存储在文件中。只需在某个编辑器中打开vulns.json,很可能会出现"{'count': 1000, ... 而不是{"count": 1000, ...

它由json.load 打开,但被转换为字符串(参见this 表)。

因此,您应该退后一步,看看在保存到文件期间会发生什么。您从响应中获取一些内容,但将字符串解码值转储到文件中。不妨试试

json.dump(response.json(), outfile)

(或者只使用您已经提供的data 变量)。

这应该允许您成功地将数据作为字典转储和加载。

【讨论】:

  • 谢谢你这个工作,不是我期望(或想要)的输出,但它仍然有效,我已经将答案标记为这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2015-05-14
  • 2015-09-17
  • 2019-07-30
相关资源
最近更新 更多