0

I am printing data from an excel sheet using python, the o/p is as below

{
  "categoryName":"test" ,
  "client": "xyz",
  "contents":[{'text': "While visiting any centre, it's important to carry the bill", 'type': 'text'}, {'text': 'Please get in touch with the authorised service centre for more details.', 'type': 'text'}],
  "language": "en",
  "additionalProperties": {}
}

I have to upload the above json in an api. But as json does not take ' as valid, how do i print the line to take all strings enlosed in " by default instead of '. so the o/p should look like

"contents":[{"text": "While visiting any centre, it's important to carry the bill", "type": "text"}, {"text": "Please get in touch with the authorised service centre for more details.", "type": "text"}]

code used:-

file_Path = ''.join(file_Path)
with open(file_Path) as input_file:
    reader = csv.DictReader(input_file)
    for row in reader:
        category = row["CATEGORY"]
        # print(category)
        rank = 1
        content = row['Template']
        ContentList = list(content.split(";"))
        Data = []
        ehcTemplateData = {}
        for template in ContentList:
            # print(template)
            data = {}
            data["text"] = template
            data["type"] = "text"
            Data.append(data)
            # print(Data)
            strData = str(Data)
        TemplateData["data"] = Data
        payload = "{\n  \"categoryName\":" + '"' + category + '"' + " ,\n  \"client\": \"myclient\",\n  \"contents\":" + strData + ",\n  \"language\": \"ta\",\n  \"additionalProperties\": {}\n}\n"

        response = requests.request("POST", url, headers=headers, data=payload)
        if response.status_code != 200:
            print(payload)
            print(category)
            print(response.status_code)
            print(response.text)
        print(response.status_code)
Soubhik Banerjee
  • 421
  • 4
  • 8
  • 17
  • Don't. Ever. Cobble. Together. JSON. By. Hand. ‍♂️ Create a *Python dict* with the desired structure, then put it through `json.dumps` to properly JSON-encode it. Or just pass the dict as is to [the `json=` parameter](https://docs.python-requests.org/en/master/user/quickstart/?highlight=json#more-complicated-post-requests) of requests. – deceze Apr 16 '21 at 09:50

2 Answers2

0

json.dumps should work for you:

strData = json.dumps(Data)
Sid
  • 2,174
  • 1
  • 13
  • 29
0

To send json content, use the json parameter from requests methods, it'll dump the structure (dict, list, ...) into a JSON string by itself

payload = {
  "categoryName":"test" ,
  "client": "xyz",
  "contents":[{'text': "While visiting any centre, it's important to carry the bill", 'type': 'text'}, {'text': 'Please get in touch with the authorised service centre for more details.', 'type': 'text'}],
  "language": "en",
  "additionalProperties": {}
}

response = requests.post(url,json=payload)
azro
  • 53,056
  • 7
  • 34
  • 70