I am trying to post a JSON Payload that includes a single backslash.
The expected JSON is:
{"ID" : "f760caa6-a54b-1eec-bef6-b7292029844f",
"DeviceID" : "f760caa6-a54b-1eec-bef6-a9fe0249a440",
"Type" : "FILL_LVL",
"MeasureTimestamp" : "\/Date(1656951856000 0000)\/",
"CreationTimestamp" : "\/Date(1656951852000 0000)\/",
"Value" : "14.000000"}
But the the JSON being send is:
{"ID": "f760caa6-a54b-1eec-bef6-b7292029844f",
"DeviceID": "f760caa6-a54b-1eec-bef6-a9fe0249a440",
"Type": "FILL_LVL",
"MeasureTimestamp": "\\/Date(1656951856000 0000)\\/",
"CreationTimestamp": "\\/Date(1656951852000 0000)\\/",
"Value": "14.000000"}
Therefore it gets rejected.
My code looks like this:
import json
import pyodata
import requests
import paho.mqtt.client as mqtt
# Connection to on prem SAP via Cloud Integration API
SERVICE_URL = '''XXX'''
HEADER = {'apikey': 'XXX'}
payload = {
"ID" : "f760caa6-a54b-1eec-bef6-b7292029844f",
"DeviceID" : "f760caa6-a54b-1eec-bef6-a9fe0249a440",
"Type" : "FILL_LVL",
"MeasureTimestamp" : "\/Date(1656951856000 0000)\/",
"CreationTimestamp" : "\/Date(1656951852000 0000)\/",
"Value" : "14.000000"
}
session = requests.Session()
session.headers.update(HEADER)
response = session.head(SERVICE_URL, headers={'x-csrf-token': 'fetch'})
token = response.headers.get('x-csrf-token', '')
session.headers.update({'x-csrf-token': token})
x = session.post(SERVICE_URL, data = json.dumps(payload))
print(x.text)
How can I achieve the proper payload formatting?
CodePudding user response:
You can do it in a hacky way:
payload = {
"ID" : "f760caa6-a54b-1eec-bef6-b7292029844f",
"DeviceID" : "f760caa6-a54b-1eec-bef6-a9fe0249a440",
"Type" : "FILL_LVL",
"MeasureTimestamp" : "/Date(1656951856000 0000)/",
"CreationTimestamp" : "/Date(1656951852000 0000)/",
"Value" : "14.000000"
}
session = requests.Session()
session.headers.update(HEADER)
response = session.head(SERVICE_URL, headers={'x-csrf-token': 'fetch'})
token = response.headers.get('x-csrf-token', '')
session.headers.update({'x-csrf-token': token})
x = session.post(SERVICE_URL, data = json.dumps(payload).replace('/', r'\/'))
print(x.text)
CodePudding user response:
The phenomenon that json.dumps(payload)
automatically escapes the backslash in the JSON string is correct (Cf.
So it is up to the application in the endpoint to apply the JSON spec and resolve/deserialize/unmarshal the JSON payload correctly.