byteify函数

Python自带的Json库会把json文件load成Unicode对象。

如果想要变成str对象的话,就要自己去encode。


def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input

这个函数递归的把list和dict里的Unicode对象encode成str。

抄袭过来的

import json

def json_load_byteified(file_handle):
return _byteify(
json.load(file_handle, object_hook=_byteify),
ignore_dicts=True
) def json_loads_byteified(json_text):
return _byteify(
json.loads(json_text, object_hook=_byteify),
ignore_dicts=True
) def _byteify(data, ignore_dicts = False):
# if this is a unicode string, return its string representation
if isinstance(data, unicode):
return data.encode('utf-8')
# if this is a list of values, return list of byteified values
if isinstance(data, list):
return [ _byteify(item, ignore_dicts=True) for item in data ]
# if this is a dictionary, return dictionary of byteified keys and values
# but only if we haven't already byteified it
if isinstance(data, dict) and not ignore_dicts:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.iteritems()
}
# if it's anything else, return it in its original form
return data

用法示例:

>>> json_loads_byteified('{"Hello": "World"}')
{'Hello': 'World'}
>>> json_loads_byteified('"I am a top-level string"')
'I am a top-level string'
>>> json_loads_byteified('7')
7
>>> json_loads_byteified('["I am inside a list"]')
['I am inside a list']
>>> json_loads_byteified('[[[[[[[["I am inside a big nest of lists"]]]]]]]]')
[[[[[[[['I am inside a big nest of lists']]]]]]]]
>>> json_loads_byteified('{"foo": "bar", "things": [7, {"qux": "baz", "moo": {"cow": ["milk"]}}]}')
{'things': [7, {'qux': 'baz', 'moo': {'cow': ['milk']}}], 'foo': 'bar'}
>>> json_load_byteified(open('somefile.json'))
{'more json': 'from a file'}

byteify的更多相关文章

  1. 制作Wi-Fi Ducky远程HID攻击设备

    1.介绍WIFI DUCKY 它是一个Wi-Fi控制的BadUSB设备来远程执行Ducky Scripts. 使用充当键盘的USB设备来注入攻击,Hak5 的 USB Rubber Ducky 是这种 ...

  2. Python27中Json对中文的处理

    应用场景如下:从api下载数据,json解析,存入字典,定期保存.重启程序需要加载保存的文本. 问题1:json中都是unicode串,存到文本里都是些\u*** 解决:关闭ensure_ascii开 ...

  3. python json unicode utf-8处理总结

    1.直接输出字典中文 在python中经常遇见直接print dict(字典),或者dict转json,但是没有给特定的参数,然后打印json字符串,输出的中文就成了unicode码的情况,如下: d ...

随机推荐

  1. Python数据类型-7

    什么数据类型. int 1,2,3用于计算. bool:True,False,用户判断. str:存储少量数据,进行操作 'fjdsal' '二哥','`13243','fdshklj' '战三,李四 ...

  2. 基于SSH的高校网上选课系统的质量属性的实现

    我对于基于SSH的高校网上选课系统的质量属性的实现是从可用性.性能.安全性.可维护性.易用性五个方面进行的实现. 可用性方面: 实现方式:(1)当系统试图超出限制范围来进行课程查询或选课时必须进行错误 ...

  3. PAT 1029 旧键盘

    https://pintia.cn/problem-sets/994805260223102976/problems/994805292322111488 旧键盘上坏了几个键,于是在敲一段文字的时候, ...

  4. jQuery中empty与html("")的区别对比

    简单的说empty,首先循环给后代元素移除绑定(释放内存).清除jquery给此dom的cache,然后循环removeFirstChild,而html(''),则是简单暴力的设置innerHTML ...

  5. Java并发—synchronized关键字

    synchronized关键字的作用是线程同步,而线程的同步是为了防止多个线程访问一个数据对象时,对数据造成的破坏. synchronized用法 1. 在需要同步的方法的方法签名中加入synchro ...

  6. Oracle 导入导出报错的简单处理

    这边出现报错: 简单查了下资料发现: https://blog.csdn.net/lichkui/article/details/5489708 在imp 的命令后面 增加buffer 即可 比如 i ...

  7. Oracle Gateways 方式创建dblink 连接 SQLSERVER数据库

    1. 安装多次 发现在同一个机器上面总出问题,所以建议找一个没有安装oracle的机器上面进行安装gateways 2. 下载oracle gateways 并且解压缩, 下载地址详情见官网. 下载的 ...

  8. 机器学习中的降维算法:ISOMAP & MDS

    参见:https://blog.csdn.net/Dark_Scope/article/details/53229427

  9. Django model 中的字段解释

    Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField:一个自动递增的整型字段,添加记录时它会自动增长.你通常不需 ...

  10. BZOJ1774[USACO 2009 Dec Gold 2.Cow Toll Paths]——floyd

    题目描述 跟所有人一样,农夫约翰以着宁教我负天下牛,休叫天下牛负我的伟大精神,日日夜夜苦思生 财之道.为了发财,他设置了一系列的规章制度,使得任何一只奶牛在农场中的道路行走,都 要向农夫约翰上交过路费 ...