【问题标题】:How do I replace single quotes with double quotes in a python array without replacing the single quotes in the json values?如何在不替换 json 值中的单引号的情况下用 python 数组中的双引号替换单引号?
【发布时间】:2022-08-20 18:57:07
【问题描述】:

我有一个名为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)

我在其中替换了一些布尔值:

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

它返回一个像这样的数组:

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

我想用上面数组中的双引号替换单引号,而不用替换json值中的单引号。 我尝试使用替换函数 (strmanagable.replace(\"\'\", \"\\\"\")),但它也替换了 json 值中的单引号,这是我不想要的。

  • 只需将managable 转换为 JSON,True -> true 转换将自动完成。
  • 嗨@snakecharmerb看来OP想承认你的贡献......你也会在这里发布答案吗? (这样我也可以投票给你!)

标签: python json api rest python-requests


【解决方案1】:

@snakecharmerb 解决了我的问题,我只需要将 managable 转换为 json

【讨论】:

  • 但从技术上讲,我已经向您展示了执行此操作的代码
【解决方案2】:

你在寻找这个功能json.dumps()吗?它将列表转换为字符串文字,然后 True 自动变为“真”

import json

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

输出

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

然后,如果您需要将其转换回来,请执行此操作

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多