Pass integer value in json serializable Python Object

35 Views Asked by At

I am new to Python and have been trying to resolve this. There is an AWS lambda function written in Python which calls a REST point like this:

requests.post(Url,headers=Headers,data=Payload)

Payload in the above call is being passed like this:

Payload='[{"Code": "'+someCode+'","version": "v1","itemNumber": 1,"referenceId": "'+referenceId+'","alertBody": {"customerId": "'+customerId+'"},"Context":{"Id":"'+str(payload['body']['State']['Id'])+'","Name":"Payment","Expiration":0,"Action":"","sourceTimestamp":"'+ str(int(currentTime.timestamp()))+'","sourceApp":"someApp"}}]'

However, due to a recent change in the schema at the API end where we post this Payload to, It has stopped working. The API is now expecting the "sourceTimestamp":"'+ str(int(currentTime.timestamp()))+'" field to be sent as an Integer and not String (currently it is being sent as String as shown in the payload above)

Can someone please guide me how to fix it and send the timestamp filed as an integer and not string? I want adhere to the payload format as above.

2

There are 2 best solutions below

1
pabludo8 On BEST ANSWER

Json integers must be given without double quoting them. So simply removing the double quotes arround str(int(currentTime.timestamp())) would work for your case

0
Mark Tolonen On

It would be less error-prone to generate the data from a Python object. Removing the string value would simply be not putting the data in the structure as a string:

import datetime as dt

# Fake data to make a working example
someCode = 'ABC'
referenceId = 'REF'
customerId = 'A123'
payload = {'body':{'State':{'Id':456}}}
currentTime = dt.datetime.now()
payload['body']['State']['Id']

Payload = json.dumps([
  {
    "Code": someCode,
    "version": "v1",
    "itemNumber": 1,
    "referenceId": referenceId,
    "alertBody": {
      "customerId": "A123"
    },
    "Context": {
      "Id": str(payload['body']['State']['Id']),
      "Name": "Payment",
      "Expiration": 0,
      "Action": "",
      "sourceTimestamp": int(currentTime.timestamp()),  # don't wrap in str() and won't be quoted
      "sourceApp": "someApp"
    }
  }
])

print(Payload)

Output:

[{"Code": "ABC", "version": "v1", "itemNumber": 1, "referenceId": "REF", "alertBody": {"customerId": "A123"}, "Context": {"Id": "456", "Name": "Payment", "Expiration": 0, "Action": "", "sourceTimestamp": 1711733124, "sourceApp": "someApp"}}]