Can do dumps and loads.
json dumps and loads.
Most of the time is not needed to make a HTTP message body yourself.
As show with Flask jsonify, it will dumps with
Same with Requests if eg try to send POST data.
Just send data and the underlying stuff is been take care of,using httpbin can test stuff out.
(May-13-2019, 02:10 AM)UtiliseIT Wrote: Is there a way to do this without having to import anything apart fromYes,but it depend what of you a trying to do.
json dumps and loads.
>>> import json >>> >>> message {'body': {'message': 'Successfully inserted'}, 'headers': {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}, 'statusCode': 200} >>> d = json.dumps(message) >>> d ('{"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*", ' '"Content-Type": "application/json"}, "body": {"message": "Successfully ' 'inserted"}}') >>> j = json.loads(d) >>> j {'body': {'message': 'Successfully inserted'}, 'headers': {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}, 'statusCode': 200}
Most of the time is not needed to make a HTTP message body yourself.
As show with Flask jsonify, it will dumps with
mimetype='application/json'
.Same with Requests if eg try to send POST data.
Just send data and the underlying stuff is been take care of,using httpbin can test stuff out.
>>> import requests >>> from pprint import pprint >>> >>> data = {'sender': 'Alice', 'receiver':'Bob', 'message':'We did it!'} >>> r = requests.post('http://httpbin.org/post', json=data) >>> pprint(r.json()) {'args': {}, 'data': '{"sender": "Alice", "receiver": "Bob", "message": "We did it!"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '63', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'json': {'message': 'We did it!', 'receiver': 'Bob', 'sender': 'Alice'}, 'origin': '46.246.117.13, 46.246.117.13', 'url': 'https://httpbin.org/post'} >>> >>> print(r.text) { "args": {}, "data": "{\"sender\": \"Alice\", \"receiver\": \"Bob\", \"message\": \"We did it!\"}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "63", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "python-requests/2.21.0" }, "json": { "message": "We did it!", "receiver": "Bob", "sender": "Alice" }, "origin": "46.246.117.13, 46.246.117.13", "url": "https://httpbin.org/post" }