Python 来自 Postman 的脚本编辑负载以解析字符串

Python script from Postman Edit payload to parse string

来自 Postman window 我可以使用以下有效负载将数据毫无问题地写入数据库

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"

我希望在 Postman 外部的 python 代码中用以下字符串替换它;

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"}]'

我使用以下代码进行替换;

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 打印为

"{"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"}]}"

我收到以下错误;

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

如何更正此问题?或者我有什么其他选择,因为 p 不是静态的,我不能在脚本中硬编码?

为什么不使用 json 模块?

试试这个:

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'))