skip to Main Content

I need to request post a 36-digit id with other things to a url.
This code should be sent as json.
But when I try to json.dumps() it, the initial and final quotes are also counted and as you can see I reach 38 characters and get error.

merchant_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
merchand_id_json = json.dumps(merchant_id)

#check len of merchat id and merchant id in json format
print('len merchant_id is', len(merchant_id))
print('len merchand_id_json is', len(merchand_id_json))

# Set header 
request_header = {
    'accept': 'application/json',
    'content_type': 'application/json',
}

# Send request
res = requests.post(
        url=request_url, 
        data=
        {
            "merchant_id": merchand_id_json,
        }, 
            headers=request_header)

# Check res content in terminal 
print('res =', res) 

# Check res.text in terminal
print('res.text =', res.text)

in Terminal:

len merchant_id befor json is 36
len merchand_id after json is 38
res =  <Response [200]>
res.text = {"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id may not be greater than 36 characters."},{"merchant_id":"string is not a valid uuid."}]}}

How can I convert this 36-digit id to json format without increasing the number of characters?

2

Answers


  1. You don’t need to call json.dumps() at all. Requests will convert the outgoing data to json automatically, if you use the json= argument instead of data=.

    res = requests.post(
        url=request_url, 
        json={"merchant_id": merchant_id},
        headers=request_header)
    
    Login or Signup to reply.
  2. The quotes are added by json.dumps() automatically.

    To avoid the quotes, you can just pass the merchant_id string directly in the request body without json.dumps():

    data = {
      "merchant_id": merchant_id
    }
    
    requests.post(url, data=data) 
    

    Now the request body will contain the raw merchant_id string without any quotes added.

    By passing the string directly instead of encoding to JSON, it avoids the extra quotes added by json.dumps(). This prevents increasing the character length.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search