无法分析json字符串索引必须是整数

2024-10-01 07:22:14 发布

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

无法分析数据

我刚印了data = json.loads(somepostmessage)

数据输出:

{'number': 'INC0010021', 'title': 'ghjghjgh', 'description': 'test creating sericenow tickets through post', 'state': 'New', 'priority': 'Planning', 'assigned_to': '', 'caller_id': ''}

代码:

 if request.method == 'POST':
    print(request.body)
    print(json.loads(request.body))
    print(type(json.loads(request.body)))
    data = json.loads(request.body)
    print(data['number'])
    return Response({"message": "Data mismatching"})

我试图通过它来解析data['number']

Error: String indices must be integers

Tags: 数据testjsonnumberdatatitlerequestbody
1条回答
网友
1楼 · 发布于 2024-10-01 07:22:14

我终于明白错在哪里了,因为json.loads(request.body)返回的是一个字符串,而不是一个字典,你把它赋给变量data。接下来,您尝试访问data['number'],但由于data是一个字符串,因此不能像前者那样用字符串索引字典。你知道吗

这看起来很奇怪(而且可能存在安全风险,所以可能有更好的方法),但这似乎可行(未经测试):

import ast
...
data = ast.literal_eval(json.loads(request.body))

相关问题 更多 >