简体   繁体   中英

How do I replace single quotes with double quotes in a python array without replacing the single quotes in the json values?

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.

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'}]

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

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