PythonRookie PythonRookie - 24 days ago 11
Python Question

How to Escape true/false boolean at python JSON string

i have following code

headers = {'Content-Type': 'application/json', 'cwauth-token': token}

payload = {'namePostfix': 'test99682', 'costModel': 'NOT_TRACKED', 'clickRedirectType': 'REGULAR', 'trafficSource':{'id': '3a7ff9ec-19af-4996-94c1-7f33e036e7af'}, 'redirectTarget': 'DIRECT_URL', 'client':{'id': 'clentIDc', 'clientCode': 'xxx', 'mainDomain': 'domain.tld', 'defaultDomain': 'domain.tld'', 'dmrDomain': 'domain.tld'', 'customParam1Available': false, 'realtimeRoutingAPI': false, 'rootRedirect': false}, 'country':{'code': 'UK'}, 'directRedirectUrl': 'http://google.co.uk'}

r = requests.post('http://stackoverflow.com', json=payload, headers=headers)


When i hit start, it gives error

NameError: name 'false' is not defined


How i can escape those false booleans at payload?

Answer

Python doesn't use false, it uses False, hence you're getting a NameError because Python is looking for a variable called false which doesn't exist.

Replace false with False in your dictionary. You've also got a few too many quotes in places, so I've removed those:

payload = {'namePostfix': 'test99682', 'costModel': 'NOT_TRACKED', 'clickRedirectType': 'REGULAR', 'trafficSource':{'id': '3a7ff9ec-19af-4996-94c1-7f33e036e7af'}, 'redirectTarget': 'DIRECT_URL', 'client':{'id': 'clentIDc', 'clientCode': 'xxx', 'mainDomain': 'domain.tld', 'defaultDomain': 'domain.tld', 'dmrDomain': 'domain.tld', 'customParam1Available': False, 'realtimeRoutingAPI': False, 'rootRedirect': False}, 'country':{'code': 'UK'}, 'directRedirectUrl': 'http://google.co.uk'}

Likewise, the opposite boolean value is True (not true), and the "null" data type is None.