python - 如何在 Python (2.6) 中将 JSON 解码为 str 而不是 unicode?

标签 python json unicode

<分区>

我有一个 JSON 格式的配置文件,其中包含一些字符串变量(始终为 ascii)。默认情况下,这些字符串被解码为 un​​icode,但由于我必须将这些变量传递给我的 Python C 扩展,所以我需要将它们作为普通的 Python 字符串。目前,我正在使用 str(unicode) 来转换 JSON 字符串,但我将不胜感激更优雅、更简洁的解决方案。

有没有办法使用自定义 JSONDecoder 或对象 Hook 将默认转换从字符串更改为 unicode?

最佳答案

如果您不愿意失去一些速度,就不会。如果稍微慢一点是可以的,您必须考虑使用普通 json.loads 并递归转换为 str 可能更便宜并且可能更快。

综上所述,如果您确实希望 loads 返回的字符串非常糟糕 以接受通过扩展本不希望的代码,那么这是一个可能的结果(主要是通过扩展copy-n-paste) 这是愚蠢的,感谢 Lennart 让我看到了曙光(即,你只需要扩展 JSONDecoder 和一些技巧):

import json
from json import decoder, scanner

from json.scanner import make_scanner
from _json import scanstring as c_scanstring

_CONSTANTS = json.decoder._CONSTANTS

py_make_scanner = scanner.py_make_scanner

# Convert from unicode to str
def str_scanstring(*args, **kwargs):
    result = c_scanstring(*args, **kwargs)
    return str(result[0]), result[1]

# Little dirty trick here
json.decoder.scanstring = str_scanstring

class StrJSONDecoder(decoder.JSONDecoder):
    def __init__(self, encoding=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, strict=True,
            object_pairs_hook=None):
        self.encoding = encoding
        self.object_hook = object_hook
        self.object_pairs_hook = object_pairs_hook
        self.parse_float = parse_float or float
        self.parse_int = parse_int or int
        self.parse_constant = parse_constant or _CONSTANTS.__getitem__
        self.strict = strict
        self.parse_object = decoder.JSONObject
        self.parse_array = decoder.JSONArray
        self.parse_string = str_scanstring
        self.scan_once = py_make_scanner(self)

# And another little dirty trick there    
_default_decoder = StrJSONDecoder(encoding=None, object_hook=None,
                               object_pairs_hook=None)

json._default_decoder = _default_decoder

j = {1:'2', 1.1:[1,2,3], u'test': {12:12, 13:'o'}}
print json.loads(json.dumps(j))

关于python - 如何在 Python (2.6) 中将 JSON 解码为 str 而不是 unicode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4723535/

相关文章:

json - Google Protobuf - 缺少类型注册表的描述符

Python 和 BeautifulSoup 编码问题

python - 无法从 tf.keras 模型 -> 量化卡住图 -> 带有 TOCO 的 .tflite

python - 按年份和季度对日期列表进行排序

javascript - 从 ASP.NET 中的操作方法检索 Json 对象

python - 如何将unicode下标与字符串格式结合起来

objective-c - 在 Objective-C 中匹配 CJK 扩展 B

python - 合并具有列表 init 的字典列表

python:使用 xmllint 时子进程通信无限期等待

C# 将多个 JSON 集合反序列化为单个 List<T>