Search code examples
pythonappendpayload

when appending a item getting string indices must be integers error-python


I am a very beginner and struggling with a POST Request. I would like to have a conditional variable in payload

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"})

This code report error "string indices must be integers" How can i solve this


Solution

  • json.dumps() function converts a Python object into a json string. It returns a python string representing the json string. You cannot access it like json. You could assign your data in as a dictionary like this

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

    and for json

    payload_json = json.dumps(payload)