追加项目时获取字符串索引必须是整数错误-python

问题描述 投票:0回答:1

我是一个非常初学者,正在努力处理 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"})

此代码报告错误“字符串索引必须是整数” 我该如何解决这个问题

python append payload
1个回答
0
投票

json.dumps() 将字典转换为字符串,这就是为什么 Payload[0] 输出“{”,因为它正在索引字符串中的第一个字符,所以当您执行 Payload["guests"] 时,您正在索引一个串串串

© www.soinside.com 2019 - 2024. All rights reserved.