美文网首页elasticsearch
中文编码json数据操作(by Python)

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

作者: 风驰电掣一瓜牛 | 来源:发表于2017-07-20 14:28 被阅读32次

现在有一个问题:
通过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?

相关文章

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

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

  • 文本/数据操作

    大文件读取 json 中文编码问题: 排序: url中文转码(python3) csv 文件操作模式 xml lx...

  • 2018-07-25

    关于Python2.7里把中文写入json文件 1.设置文件格式2.设置数据编码

  • python常用语法指南

    1. 输出json 文件 当在python中将 dic 转成json 之后,很多中文变成 未编码的中文,需要加en...

  • python学习笔记|数据格式化——JSON解析

    Json解析包括编码(encoding)与解码(decoding)。编码是将python数据类型转换为json格式...

  • Python输出显示的问题

    解决python中包含UTF-8编码中文的列表或字典的输出 import json print json.dump...

  • json与python

    Python 对象编码成 JSON 字符串 json.dumps 用于将 Python 对象编码成 JSON 字符...

  • Python读写JSON数据

    1. Python数据结构转换为JSON对象 json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中...

  • 网络编程报错

    1、python 字典json字符串中文乱码怎么办? #这是因为中文以 unicode 编码了,而默认是以ASCI...

  • python处理json格式数据

    json模块提供了一种很简单的方式来编码和解码JSON数据。编码过程是把python对象转换为JSON对象的一个过...

网友评论

    本文标题:中文编码json数据操作(by Python)

    本文链接:https://www.haomeiwen.com/subject/ffodkxtx.html