My Python code, which I obtained from POSTMAN, throws an error with the string
"code":"E101","message":"JSON Error: Syntax error, malformed JSON"}"
although in POSTMAN, the request was successful and produced the expected JSON result.
below is my python code
import requests
url = "APIURL"
payload={'data': '{
"authenticate":{
"apikey":"ABCSHF"
},
"services":[
{
"call":"history/API",
"identifier":{
"search":"desc"
}
}
]
}'}
files=[
]
headers = {
}
response = requests.request("POST", url, headers=headers, json=payload, files=files)
print(response.text)
Can anyone please help me on this.
CodePudding user response:
I guess you should get clearness what did you code ;):
requests
parse a dict to a JSON internally, see explanation here
import json
from pprint import pprint
# some JSON string:
json_string = '{ "authenticate":{ "apikey":"ABCSHF" }, "services":[ { "call":"history/API", "identifier":{ "search":"desc" } } ] }'
# parse JSON string to dict:
json_as_dict = json.loads(json_string)
pprint(json_as_dict)
# >> {'authenticate': {'apikey': 'ABCSHF'},
# >> 'services': [{'call': 'history/API', 'identifier': {'search': 'desc'}}]}
incorrect_payload_as_dict = {'data': json.dumps(json_as_dict)}
pprint(incorrect_payload_as_dict)
# >> {'data': '{"authenticate": {"apikey": "ABCSHF"}, "services": [{"call": '
# >> '"history/API", "identifier": {"search": "desc"}}]}'}
correct_payload_as_dict = {'data': json_as_dict}
pprint(correct_payload_as_dict)
# >> {'data': {'authenticate': {'apikey': 'ABCSHF'},
# >> 'services': [{'call': 'history/API',
# >> 'identifier': {'search': 'desc'}}]}}