尝试从JSON获取数据时出现TypeError

2024-04-29 06:52:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在JSON中打印特定数据,但出现以下错误:

Traceback (most recent call last):
  File "script.py", line 47, in <module>
    print(link['data.file.url.short'])
TypeError: 'int' object has no attribute '__getitem__'

以下是JSON:

{ 
   "status":true,
   "data":{ 
      "file":{ 
         "url":{ 
            "full":"https://anonfile.com/y000H35fn3/yuh_txt",
            "short":"https://anonfile.com/y000H35fn3"
         },
         "metadata":{ 
            "id":"y000H35fn3",
            "name":"yuh.txt",
            "size":{ 
               "bytes":0,
               "readable":"0 Bytes"
            }
         }
      }
   }
}

我正在尝试获取data.file.url.short,这是url的短值

以下是相关剧本:

post = os.system('curl -F "file=@' + save_file + '" https://anonfile.com/api/upload')
link = json.loads(str(post))

print(link['data.file.url.short'])

谢谢


Tags: 数据httpstxtcomjsonurldatalink
3条回答

您正在捕获os.system创建的进程的返回代码,它是一个整数

为什么不使用urllib模块中的request类在python中执行该操作呢

import urllib.request
import json

urllib.request.urlretrieve('https://anonfile.com/api/upload', save_file)
json_dict = json.load(save_file)
print(json_dict['data']['file']['url']['short'])  # https://anonfile.com/y000H35fn3

或者,如果不需要保存文件,可以使用请求库:

import requests

json_dict = requests.get('https://anonfile.com/api/upload').json()
print(json_dict['data']['file']['url']['short'])  # https://anonfile.com/y000H35fn3

os.system()不返回命令的输出;它返回命令的退出状态,它是一个整数

如果要捕获命令的输出,请参见this question

除了@John Gordon提到的os.system()返回值之外,我认为访问data.file.url.short的正确语法是link['data']['file']['url']['short'],因为json.loads返回dict

相关问题 更多 >