中文编码json数据操作(by Python)

现在有一个问题:
通过json.loads()函数读取的数据是unicode的,后续没法处理。

解决方法:
通过json.loads函数中的object_hook参数指定解析方式

代码如下:

import sys 
import json

g_charset= 'utf-8'

def _byteify(data, ignore_dicts = False):
    if isinstance(data, unicode):
        return data.encode(g_charset)
    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()
        }   
    return data

def json_loads_byteified(json_text):
    return _byteify(
        json.loads(json_text, object_hook=_byteify),
        ignore_dicts=True
    )   

line = file(sys.argv[1]).readline()
data = json_loads_byteified(line.strip())

print json.dumps(data, ensure_ascii=False, indent=2)

参考:

How to get string objects instead of Unicode from JSON?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,961评论 0 38
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,087评论 19 139
  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,794评论 0 5
  • pyton review 学习指南 https://www.zhihu.com/question/29138020...
    孙小二wuk阅读 1,086评论 0 2
  • 日期 //日期格式yyyyPatternsDict.date_y= /^(\d{4})$/;//日期格式yyyy-...
    简单的土豆阅读 349评论 0 1