简体   繁体   中英

Reformat JSON file for Python Requests payload (add \n, \t)

I am working with requests library at the moment. I used Postman to create a request, and it works.

url = url

payload = "{\n    \"key\" : {\n\t\t\"inner_key\": [\n    \t\t{\n        \t\t\"inner_key2\": \"inner_value\",\n        \t\t\"inner_key3\": \"inner_value2\"\n    \t\t}\n\t\t],\n}"

headers = {
  'Authorization': 'token',
  'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers,  data = payload)
print(response.text.encode('utf8'))

However, when I try to pass a json to payload, it doesn't work anymore. Returns an empty string.

jsonfile = {"key" : {
    "inner_key": [
        {
            "inner_key1": "inner_value",
            "inner_key2": "inner_value2"
        }
    ],}}

url = url

payload = jsonfile
headers = {
  'Authorization': 'token',
  'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers,  data = payload)
print(response.text.encode('utf8'))

Is there a way to reformat jsonfile so that it includes \n and \t? I am new to json format, so not sure how to go about it.

you need to pass a string to the data argument which only requires a minimal adjustement:

import json
payload = json.dumps(jsonfile) 

The funciton json.dumps will read your dictionary jsonfile and give you a nice string which looks somewhat like what you typed in the first-place. In fact you get

# payload = 
'{"key": {"inner_key": [{"inner_key1": "inner_value", "inner_key2": "inner_value2"}]}}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM