尝试从json文件获取数据时出错

时间:2018-08-08 16:51:10

标签: python json discord.py

尝试从json文件获取数据时出现错误。

当我使用此代码时,它是issuer_name的KeyError:

@ticket.command(pass_context=True)
@commands.has_role("Tech Support Lead")
async def info(self,ctx):
    ticket = ctx.message.content[13:]
    if ticket == "":
        await self.bot.say("Please supply a ticket id")
        return
    with open("data/tickets.json", "r") as f:
        tickets = json.load(f)
    print(tickets[ticket]["issuer_name"])

它是TypeError(当我使用此代码时,列表索引必须是int或slices,而不是str):

@ticket.command(pass_context=True)
@commands.has_role("Tech Support Lead")
async def info(self,ctx):
    ticket = ctx.message.content[13:]
    if ticket == "":
        await self.bot.say("Please supply a ticket id")
        return
    with open("data/tickets.json", "r") as f:
        tickets = json.load(f)
    print(tickets[ticket]["ticket_data"]["issuer_name"])

这是我的JSON文件:

   {"amount_of_open_tickets": 1, "13": {"ticket_data": [{"issuer_id": 
   "244204285729046528", "issuer_name": "Veestire", "ticket_message": "l", 
   "claimed": null}]}}

1 个答案:

答案 0 :(得分:0)

这是一个可行的示例。您的ticket_data密钥的值是一个列表,而不是单个对象

a="""{"amount_of_open_tickets": 1, "13": {"ticket_data": [{"issuer_id": 
   "244204285729046528", "issuer_name": "Veestire", "ticket_message": "l", 
   "claimed": null}]}}"""
b=json.loads(a)
b['13']["ticket_data"][0][u'issuer_name'] #u'Veestire'