Python-从URL、里面的控制和特殊字符获取JSON

标签 python json python-3.x

我一直在尝试使用典型方法从 URL 获取 JSON,例如:

import urllib.request, json 
with urllib.request.urlopen("my_url") as url:
    data = json.loads(url.read().decode())

尽管如此,由于 JSONDecodeError 失败,因为某个括号内有一个控制字符

{..."\tvalue"...}

我确实修改了我的源数据以不包含控制字符(我可能并不总是能够做到这一点),但 python 一直说控制字符在那里。

我决定将我的 url 响应放入字符串中,并替换内部控制字符

my_str = url.read()
my_str = my_str.replace('"\\t','"')

但是这样,整个 JSON 文件中的特殊字符就会以奇怪的方式被替换:{...sábado...} 变成 {...sa\cxx\c1bado } 或类似的东西。

如何在不破坏特殊字符的情况下清理来自控制字符的 JSON 输入?

编辑:

抱歉,在第一个答案中忘记提及一些内容:

我确实尝试添加 strict=False,但后来我的 JSON 变得......好吧,疯了。双引号变成了单引号,其中一些会消失,所以当我打印它时,我得到了类似的东西:

{
    'some_key':'some_value',
    'another_key':'another_value_without_closing_quote,
    a_key_without_opening_quote': 'value'
}

没有任何线索说明为什么会出现这种情况。

最佳答案

您可以通过指定 strict=False 来允许控制字符。

根据docs :

If strict is False (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.

data = json.loads(url.read().decode(), strict=False)

关于Python-从URL、里面的控制和特殊字符获取JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48552918/

相关文章:

python - 在 python 中导入 sikuli 模块时遇到问题。我正在使用 RIDE 运行 python 脚本

javascript - 在 AngularJS 中聚合对象

python - 从字符串和列表的元组中以字符串形式返回所有值

android - 将字符串转换为 json 对象

php - 从$ json打印youtube元数据

python - 计算嵌套列表中每个位置的出现次数

arrays - 在 Python 中使用字典填充数组是否会创建重复的字典?

python - 在 PySpark Streaming 中读取同一文件上具有不同架构的 CSV 文件

python - 更新的词典列表

python - 列表内具有相同名称的列表