在追加项目时出现字符串索引必须是整数的错误-python

-1 投票
2 回答
32 浏览
提问于 2025-04-14 17:18

我还是个初学者,正在努力理解POST请求。我想在数据中添加一个条件变量。

import json
adults=int(input(Enter no.of adults:)
childs=int(input(Enter no.of childs:)
payload = json.dumps({"dates": {"from": "check_in_date","to": 
"check_out_date"},"propertyId":"%hotel_code","leadGuest": {"birthDate": "1991-09- 
13","contact": {"address": "Address","city": "City","country": "Country","email": 
"Email_Address","phone": "MobileNo","state": "State","zip": "Zipcode"},"name": {"first": 
"First_Name","last": "Last_Name"},"title": "MR"},"reference": {"agency": 
"JhdGVQbGFuQ29kZSI6Ik1212"},"paymentDetails": {"type": "credit_card","details": {"number": 
"4111111111111111","cvv": "123","expiry": {"month": "01","year": "2028"},"name": {"first": 
"First_Name","last": "Last_Name"}}},"rooms": [{"roomCode": "roomCode","roomId": 
"roomId","rateCode": "rateCode","ratePlanId": "ratePlanId","expectedPrice": {"amount": 
"amount","currency": "USD"},"guests": [{"birthDate": "1992-09-13","contact": {"address": 
"Address","city": "City","country": "Country","email": "%Email_Address","phone": 
"MobileNo","state": "State","zip": "Zipcode"},"name": {"first": "First_Name","last": 
"Last_Name"},"title": "MR"}]}],"meta": []})
 print(payload[0]) #output is {
 print(payload["guests"] #output is string indices must be integers
 if adults == 2:
    payload['guests'].append({"birthDate": "1980-09-13","name": {"first": 
"Adultguest","last": "test"},"title": "MR"})
if childs == 1:
    payload['guests'].append({"birthDate": "2018-09-13","name": {"first": 
"childguest","last": "test"},"title": "MR"})

这段代码报错了,提示“字符串索引必须是整数”。我该怎么解决这个问题呢?

2 个回答

0

json.dumps() 是把一个字典转换成字符串,这就是为什么 payload[0] 输出 "{" 的原因,因为它是在获取字符串的第一个字符。所以当你用 payload["guests"] 时,其实是在用一个字符串去索引另一个字符串。

0

json.dumps() 函数的作用是把一个 Python 对象转换成一个 json 字符串。它会返回一个表示 json 字符串的 Python 字符串。你不能像访问 json 那样去访问它。

你可以把你的数据以字典的形式这样赋值:

 payload = {"dates": {"dates": {"from": "check_in_date","to":

           .....

            }

然后是 json:

payload_json = json.dumps(payload)

撰写回答