Python script from Postman Edit payload to parse string

750 views Asked by At

From the Postman window I am able to write data to a database without issues using the following payload

payload = "{\"Items\": [{\"SystemId\": \"FPC\",\"EngagementId\": \"40211\",\"DE_LOD_INF_LAND_LAT\":\"20.000000\", \"DE_LOD_INF_LAND_LONG\":\"50.000000\"},{\"SystemId\": \"FPC\",\"EngagementId\":\"67039\",\"DE_LOD_INF_LAND_LAT\":\"0.000000\", \"DE_LOD_INF_LAND_LONG\": \"60.000000\"}]}\r\n"

I wish to substitute this with the following string in a python code outside Postman;

p='[{"SystemId": "FPC", "EngagementId": "40211", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}, {"SystemId": "FPC", "EngagementId": "67039", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}]'

I do the substitution using the following code;

url = "url"

payload = '"{\"Items\": '+ p + '}"'
headers = {
  'Authorization': access_token.split('"')[3],
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))

p prints as

"{"Items": [{"SystemId": "FPC", "EngagementId": "40211", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}, {"SystemId": "FPC", "EngagementId": "67039", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}]}"

I get the following error;

b'{"Messages":[{"code":"WEBSVC0020","Message":"The request object could not be parsed. Please check the structure of your request.","NotificationType":"Error","iserror":true}]}'

How can I get this corrected? Or what other options do I have because p is not static and I cant hardcode in the script?

1

There are 1 answers

1
baduker On BEST ANSWER

Why not use the json module?

Try this:

import json

url = "url"
p = '[{"SystemId": "FPC", "EngagementId": "40211", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}, {"SystemId": "FPC", "EngagementId": "67039", "DE_LOD_INF_LAND_LAT": "0.000000", "DE_LOD_INF_LAND_LONG": "0.000000"}]'
payload = {'Items': json.loads(p)}

print(payload['Items'][0]['SystemId'])
headers = {
    'Authorization': access_token.split('"')[3],
    'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=json.dumps(payload))

print(response.text.encode('utf8'))