我有一个 python 2.7 字典,例如{u"eat": u"糖果", u"drink": u"café"}
,我需要使用 JSON 传输它。JSON 字符串必须是常规 ASCII,并且必须少于 256 个字符。
到目前为止,我已经编写了这个代码:
import json
def payload_to_json(payload, max_size = 256):
while True:
json_string = json.dumps(payload, separators = (',', ':'))
if len(json_string) <= max_size:
return json_string
max_length, found_key = 0, None
for key, value in payload.iteritems():
length = len(value)
if length > max_length:
max_length = length
found_key = key
if max_length == 0:
return "" # just in case max_size is really low
payload[found_key] = payload[found_key][:-1] # remove one char
它按预期工作:
>>> payload = {u"eat": u"糖果", u"drink": u"café"}
>>> print payload_to_json(payload)
{"drink":"caf\u00e9","eat":"\u7cd6\u679c"}
>>> print payload_to_json(payload, max_size=41)
{"drink":"caf","eat":"\u7cd6\u679c"}
>>> print payload_to_json(payload, max_size=35)
{"drink":"ca","eat":"\u7cd6\u679c"}
>>> print payload_to_json(payload, max_size=34)
{"drink":"c","eat":"\u7cd6\u679c"}
>>> print payload_to_json(payload, max_size=30)
{"drink":"c","eat":"\u7cd6"}
>>> print payload_to_json(payload, max_size=21)
{"drink":"","eat":""}
>>> print payload_to_json(payload, max_size=20)
在我看来,应该有一种方法来优化它!我真的一次剥一个角色,感觉很不对劲。
我的问题非常接近这个问题,除了我使用 python 2.7,而且只要源字符串包含非 ASCII unicode 字符,json 编码器就会产生相当长的 JSON 字符串。
另外,我很确定这将与 UTF-16 代理对中断......