简体   繁体   中英

Switching inner single quotes to double quotes and outer double quotes to single quotes in stringified list

I have a list of dictionaries that is being dynamically populated with data from another list. This list of dictionaries is then being used as the body parameter in a request. The list of dictionaries must be a string for the request to succeed.

The problem is that when I dynamically populate the list of dictionaries, str(list_of_dicts), it puts double quotes around the string object and single quotes around everything inside. I need it to be just the opposite, with double quotes wrapping the string and single quotes on everything inside.

I have tried replace, str, repr, join and json.dumps to no avail as of yet.

def insert_header(self, request):
        pid = request.meta['pid']
        pa = request.meta['pa']
        url = request.url
        pid = [x.split('ern:product::')[-1] for x in pid]

        body = [
            {"id":"1234567","variables":{"id":"ern:product::pid"}},
            {"id":"1234567","variables":{"id":"ern:product::pid"}},
            {"id":"1234567","variables":{"id":"ern:product::pid"}}
        ]
        
        if len(pid) == len(body):
            for counter, i in enumerate(body):
                i["variables"] = {"id":"ern:product::" + pid[counter]}

        body = str(body)
        body.replace("'", '"')
 
        return Request(url, method='POST', meta=request.meta, body=body, callback=self.check_header, **self.parse_page_kwargs)

What is really frustrating is that in a python shell I can copy the failing list of dictionaries (the list with the quotes the wrong way) and do: list_of_dicts.replace("'", '"') and it returns exactly what I need, it's just not changing like that when I run the code. Thank you in advance for any suggestions.

I think you should remove the line body = body[1:-1] .

str(body) does not put any quotes at the beginning and end. So you are removing part of the actual data.

You can also use body = json.dumps(body) and no need any further replacement.

to see the actual content of the str use print(body) . It should look like:

[{"id": "1234567", "variables": {"id": "ern:product::pid"}}, {"id": "1234567", "variables": {"id": "ern:product::pid"}}, {"id": "1234567", "variables": {"id": "ern:product::pid"}}]

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