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. D. Mysterious Crime

    链接 [http://codeforces.com/contest/1043/problem/D] 题意 给你一个m*n的矩阵(m<=10,n<=1e5), 每一行的数字是1到n里不同的数 ...

  2. “Linux内核分析”实验报告

    Linux内核分析:实验一 潘俊洋 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-100002900 ...

  3. mysql执行 sql文件遇到USING BTREE ) ENGINE=MyISAM DEFAULT CHARSET=utf8错误

    使用navcat在导入别人发的mysql数据的时候,报了下面这个错误: [Err] 1064 - You have an error in your SQL syntax; check the man ...

  4. [日常工作]vCenter下虚拟机设置与宿主机时间同步的方法

    1. ESXi 能够实现CPU超售 同事开启多与CPU个数的虚拟机 不通的虚拟机采用了时间分片的处理, 所以有时候虚拟机内的时间可能会比宿主机的时间过的更慢, 越来越久之后虚拟机的时间就会比较离谱了. ...

  5. Linux下DB2命令学习及整理

    DB2相关数据库命令 1.数据库实例的启动首先要启动数据库的实例,即切换到db2inst1用户(注:db2inst1用户为当前数据库的实例),然后执行db2start启动数据库的实例 [root@lo ...

  6. pandas获取当前时间

    datetime.now()用于获取当前的日期和时间 print pd.datetime.now() #encoding:utf8 import pandas as pd print("(p ...

  7. 周刷题第一期总结(two sum and two numbers)

    由于深深的知道自己是事件驱动型的人,一直想补强自己的薄弱环节算法,却完全不知道从哪里入手.所以只能采用最笨的办法,刷题.从刷题中遇到问题就解决问题,最后可能多多少少也能提高一下自己的渣算法吧. 暂时的 ...

  8. error eslint@5.12.0: The engine "node" is incompatible with this module.

    初始化 react项目时报错: error eslint@5.12.0: The engine "node" is incompatible with this module. E ...

  9. ComboBox中如何嵌套TreeView控件

      在ComboBox中嵌套TreeView控件,有时候我们在设计界面的时候,由于界面设计的需要,我们需要将TreeView控件嵌套在ComboBox中,因为TreeView控件实在是太占用地方了,要 ...

  10. IDEA Maven 项目默认编译项目为JDK 1.5

    昨天晚上遇到一个问题,我在idea中创建了有个maven项目,想使用jdk1.8的lambda表达式,结果提示我错误,是1.8才可以.当时我想我的jdk就是1.8啊.经过各种搜索,才知道maven默认 ...