Home > Net >  How do I replace single quotes with double quotes in a python array without replacing the single quo
How do I replace single quotes with double quotes in a python array without replacing the single quo

Time:08-14

I have an array called managable:

r = requests.get("https://discord.com/api/v8/users/@me/guilds", headers = {
    "Authorization": f"Bearer {access_token}"
})

guilds = r.json()
managable = []

for guild in guilds:
    if int(guild["permissions"]) & 32 != 0:
        managable.append(guild)

where I replace some boolean values in it:

strmanagable = str(managable).replace("True", '"true"').replace("False", '"false"').replace("None", '"none"')

and it returns an array like this:

[{'id': '0', 'name': '\'something\''}, {'id': '1', 'name': '\'two\''}]

I want to replace the single quotes with double quotes in the array above, without replacing the single quotes in the json values. I tried using the replace function (strmanagable.replace("'", "\"")), but it replaces single quotes in the json values too, which I don't want.

CodePudding user response:

@snakecharmerb solved my question, I just had to convert managable to json

CodePudding user response:

Are you look for this function json.dumps()? It converts the list into a string literal, then True becomes 'true' automatically

import json

lis1 = [{'id': '0', 'name': True}, {'id': '1', 'name': False}, {'id': '2', 'name': 'two'}]
lis1 = json.dumps(lis1)

Output

'[{"id": "0", "name": true}, {"id": "1", "name": false}, {"id": "2", "name": "two"}]'

Then if you need to convert it back, do this

lis2 = json.loads(lis1)
print(lis2)

[{'id': '0', 'name': True},
 {'id': '1', 'name': False},
 {'id': '2', 'name': 'two'}]
  • Related