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. Daily scrum 12.24

    平安夜闲得想来一遍scrum,添加了之前ui组的数据库问题修复任务. 其实是之前忘记在任务中添加了.现在基本修复完成. Member Today’s task 林豪森 与学霸其他小组交流,处理整合问题 ...

  2. git 的安装及使用

    一.Git的安装和使用 1.1 Linux下版本库的创建 1.1.1 创建一个版本库 repository,在一个合适的地方创建一个空目录: root@zengyue:/# mkdir -p /hom ...

  3. 『编程题全队』"Gugua"事务管理系统项目宣传文案

    一.项目简介 1.项目简介 Gugua是为了解决有事务管理需要的人群的痛苦, 他们需要 一个便利和高效的个人和团体事务管理平台,但是现有的方案并没有很好地解决这些需求,我们有独特的办法是提供跨平台的软 ...

  4. JavaScript中给onclick绑定事件后return false遇到的问题

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. [转帖]/etc/security/limits.conf的含义

    https://www.cnblogs.com/pzk7788/p/7250723.html /etc/security/limits.conf 是 Linux 资源使用配置文件,用来限制用户对系统资 ...

  6. Linux基础学习(9)--文件系统管理

    第九章——文件系统管理 一.回顾分区和文件系统 1.分区类型: 2.分区表示方法: 3.文件系统: 二.文件系统常用命令 1.df命令.du命令.fsck命令和dump2fs命令: (1)文件系统查看 ...

  7. 反编译微信小程序

    最近看了个微信小程序古诗词全集,想知道他的前后端是怎么实现的,所以就想到了反编译.小程序安装后会有个wxapkg格式的文件存在/data/data/com.tencent.mm/MicroMsg/** ...

  8. js 錯誤

    try{ //需要被檢測是否拋出錯誤 } catch(err) { //錯誤處理代碼 } try.catch成對出現 throw:拋出錯誤 當錯誤發生時,javascript引擎停止運行,并生成一個錯 ...

  9. codeforces604B

    More Cowbell CodeForces - 604B Kevin Sun wants to move his precious collection of n cowbells from Na ...

  10. mvc 验证登录

    很多时候,我们需要多个页面验证用户是否登录 有2中方法. 一种是继承 Attrbuite属性,添加验证,这个可以网上搜索. 我一般使用下面的方式 创建BaseWebController继承Contro ...