更新12/30/2014

实现这一目标的最简单方法是使用JSONDecoder的object_hook回调,如下面的旧答案中所述.但是,由于这需要对数据中的每个键值对进行额外的函数调用,这可能会对性能产生影响.

所以,如果你真的想改变json处理None的方式,你需要深入挖掘一下. JSONDecoder使用扫描程序在JSON输入中查找某些令牌.不幸的是,这是一个函数,而不是一个类,因此子类化并不那么容易.扫描仪功能称为py_make_scanner,可以在json / scanner.py中找到.它基本上是一个函数,它将JSONDecoder作为参数获取并返回scan_once函数. scan_once函数接收字符串和当前扫描仪位置的索引.

一个简单的自定义扫描仪功能可能如下所示:

import json

def make_my_scanner(context):

# reference to actual scanner

interal_scanner = json.scanner.py_make_scanner(context)

# some references for the _scan_once function below

parse_object = context.parse_object

parse_array = context.parse_array

parse_string = context.parse_string

encoding = context.encoding

strict = context.strict

object_hook = context.object_hook

object_pairs_hook = context.object_pairs_hook

# customized _scan_once

def _scan_once(string, idx):

try:

nextchar = string[idx]

except IndexError:

raise StopIteration

# override some parse_** calls with the correct _scan_once

if nextchar == '"':

return parse_string(string, idx + 1, encoding, strict)

elif nextchar == '{':

return parse_object((string, idx + 1), encoding, strict,

_scan_once, object_hook, object_pairs_hook)

elif nextchar == '[':

return parse_array((string, idx + 1), _scan_once)

elif nextchar == 'n' and string[idx:idx + 4] == 'null':

return 'Cat', idx + 4

# invoke default scanner

return interal_scanner(string, idx)

return _scan_once

现在我们只需要一个JSONDecoder子类,它将使用我们的扫描器而不是默认扫描器:

class MyJSONDecoder(json.JSONDecoder):

def __init__(self, encoding=None, object_hook=None, parse_float=None,

parse_int=None, parse_constant=None, strict=True,

object_pairs_hook=None):

json.JSONDecoder.__init__(self, encoding, object_hook, parse_float, parse_int, parse_constant, strict, object_pairs_hook)

# override scanner

self.scan_once = make_my_scanner(self)

然后像这样使用它:

decoder = MyJSONDecoder()

print decoder.decode('{"field1":null, "field2": "data!"}')

旧的答案,但如果你不关心另一个函数调用的性能影响仍然有效:

您需要使用特殊的object_hook方法创建JSONDecoder对象:

import json

def parse_object(o):

for key in o:

if o[key] is None:

o[key] = 'Cat'

return o

decoder = json.JSONDecoder(object_hook=parse_object)

print decoder.decode('{"field1":null, "field2": "data!"}')

# that will print: {u'field2': u'data!', u'field1': u'Cat'}

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.

所以parse_object将获得一个字典,可以通过用’Cat’交换所有None值来操作.然后将在输出中使用返回的对象/字典.

python自定义类型转换_Python JSONDecoder自定义null类型的转换相关推荐

  1. python学习类型转换_Python学习总结5:数据类型及转换

    Python提供的基本数据类型主要有:整型.浮点型.字符串.列表.元组.集合.字典.布尔类型等等. Python可以用一些数据类型函数,直接进行转换: 函数                       ...

  2. python复数类型转换_python复数类

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! a = trueb = falseprint (a = %s, b = %s % ...

  3. python函数自定义教程_Python中自定义函数的教程

    在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 我们以自定义一个求绝对值的my_abs函数 ...

  4. python中如何自定义函数_Python中自定义函数的教程

    在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 我们以自定义一个求绝对值的my_abs函数 ...

  5. python如何自定义函数_python如何自定义函数_后端开发

    c语言特点是什么_后端开发 c语言特点是:1.语言简洁.紧凑,使用方便.灵活:2.运算符丰富:3.数据结构丰富,具有现代化语言的各种数据结构:4.具有结构化的控制语句:5.语法限制不太严度格,程序设计 ...

  6. python自定义异常捕获_python怎么自定义捕获错误

    异常捕捉: try: XXXXX1 raise Exception("xxxxx2") except (Exception1,Exception2,--): xxxx3 else: ...

  7. python分割函数_Python应用——自定义函数:分割PDF文件函数

    案例 将一个 pdf 文件按要求分割为几个部分.比如说一个pdf有20页,分成5个pdf文件,每个pdf文件包含4页.设计函数实现? Python代码 from PyPDF2 import PdfFi ...

  8. python内置类型_Python内置对象类型

    核心数字类型: 数字:int,long,float,complex,bool 字符:str,unicode 列表:list 字典:dict 元组:tuple 文件:file 其他类型:集合(set), ...

  9. python 矩阵类型转换_python矩阵中float转int

    问题:numpy定义的矩阵A中所有元素为float类型,现要求将A中所有元素转化为int类型. 修改时间:2017年5月24日 >>>import numpy as np >& ...

最新文章

  1. html中锚点的应用【本页面跳转】
  2. 抗击疫情,AI一直在行动
  3. python知网查重_用Python写了个检测抄袭/文章去重算法(nshash)
  4. 在AngularJS控制器之间共享数据
  5. Handle In-Day Changes
  6. 引用:编写高性能Web应用程序的10个技巧(一)
  7. Druid 配置_LogFilter
  8. 安装Scrapy失败的解决方法
  9. )C# Enum,Int,String的互相转换 枚举转换
  10. Kotlin教程(一):走进Kotlin的世界
  11. JMX详解及JConsole使用
  12. 蓝桥杯 青少年创意编程大赛 scratch 组、中国电子学会scratch等级考试等
  13. 阿里p7架构师:三年经验应该具备什么样的技能?
  14. 微信群总是有人发广告?看我用Python写一个自动化机器人消灭他!
  15. 在python中使用autoit_在Python中调用AutoIt函数
  16. 计算机文化宣传普及知识展,浅谈计算机文化
  17. 【NOIP模拟赛】【数学真奇妙系列】纸盒子
  18. Linux ls -l 名:命令详解
  19. [转帖]中国民间秘术
  20. NoSQL Manager for MongoDB Professional 算法

热门文章

  1. postman压力测试_如何用Postman简单做接口自动化
  2. edge无法打印pdf_一文搞定PDF无法复制/打印/编辑
  3. python3多线程编程_Python3 多线程编程
  4. markdown生成html不出效果,mdeditor: 简单markdown编辑器,同步预览html效果。不依赖任何插件,使用简单,原创,造轮子中。。。更新中。。。...
  5. form标签的action之前 加密_口令爆破之突破前端JS加密
  6. java线程池_Java 线程池 8 大拒绝策略,面试必问!
  7. Tensor看这一篇就够了!
  8. Python之对list进行切片
  9. ## CSP 201312-2 ISBN号码(C语言)(100分)
  10. Ubuntu——“系统无法检测到Intel的核心显卡”的调试笔记~