如何在python(2.6)中将JSON解码为str而不是unicode? [英] How to decode JSON to str and not unicode in Python (2.6)?

查看:181
本文介绍了如何在python(2.6)中将JSON解码为str而不是unicode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a configuration file in JSON that contains a few variables as strings (always ascii). These strings are decoded to unicode by default but since I have to pass these variables to my Python C Extensions I need them as normal Python strings. At the moment I'm using str(unicode) to convert the JSON strings but a more elegant and less verbose solution would be much appreciated.

是否可以通过自定义JSONDecoder或对象挂钩将默认转换从字符串更改为unicode?

Is there a way to change the default translation from string to unicode with a custom JSONDecoder or object hook?

推荐答案

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

Not if you're not willing to lose some speed. If being somewhat slower is OK, you have to consider that using plain json.loads and recursively converting to str is probably cheaper and maybe faster.

话虽如此,如果您确实想让loads返回的字符串严重不足以接受通过本来不是本意的扩展代码,则这是一个可能的结果(主要是通过copy-n-paste进行扩展) )这太愚蠢了,谢谢Lennart让我看到了光(即,您只需要扩展JSONDecoder和一些技巧即可):

With all that said, if you do want a loads that returns strings badly enough to accept going through extending code that wasn't meant to, here's one possible result (mostly extending through copy-n-paste) this was asinine, thanks Lennart for making me see the light (i.e., you just need to extend JSONDecoder and a couple of tricks):

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(2.6)中将JSON解码为str而不是unicode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆