He called the crowd with his disciples, and said to them,"If any want to become my followers, let them deny themseleves and take up their cross and follow me. For those who want to save their life will lose it, and those who lose their life for my sake, and for the sake fo the gospel, will save it. For what will it profit them to gain the whole world and forfeit their life? Indeed, what can they give in return for their life? Those who are ashamed of me and of my words in this adulterous and sinful generation, of them the Son of Man will also be ashamed when he comes in the glory of his Father with the holy angels."(MARK 9:34-38)

比较json/dictionary的库

在某些情况下,比较两个json/dictionary,或许这样就可以实现:

>>> a
{'a': 1, 'b': 2}
>>> b
{'a': 2, 'c': 2}
>>> cmp(a,b)        #-1或者1,代表两个dict不一样
-1
>>> c=a.copy()
>>> c
{'a': 1, 'b': 2}
>>> cmp(a,c)       #两者相同
0

但是,这只能比较两个是不是一样,不能深入各处哪里不一样的比较结果。

有这样一个库,就能解决这个问题,它就是json_tools

安装

方法1:

>>> pip install json_tools

或者

>>> easy_install json_tools

方法2:到这里下载源码:https://pypi.python.org/pypi/json_tools,然后进行安装

比较json

首先看看都有哪些属性或者方法,用万能的实验室来看:

>>> import json_tools
>>> dir(json_tools)

['builtins', 'doc', 'file', 'loader', 'name', 'package', 'path', '_patch_main', '_printer_main', 'diff', 'patch', 'path', 'print_function', 'print_json', 'print_style', 'printer']

从上面的结果中,可以看到json_tools的各种属性和方法。

我在一个项目中使用了diff,下面演示一下使用过程

>>> a
{'a': 1, 'b': 2}
>>> b
{'a': 2, 'c': 2}
>>> json_tools.diff(a,b)
[{'prev': 1, 'value': 2, 'replace': '/a'}, {'prev': 2, 'remove': '/b'}, {'add': '/c', 'value': 2}]

上面这个比较是比较简单的,显示的是b相对于a的变化,特别注意,如果是b相对a,就要这样写:json_tools.diff(a,b),如果是json_tools.diff(b,a),会跟上面有所不同,请看结果:

>>> json_tools.diff(b,a)
[{'prev': 2, 'value': 1, 'replace': '/a'}, {'prev': 2, 'remove': '/c'}, {'add': '/b', 'value': 2}]

json_tools(a,b),即b相对a发生的变化为例进行说明。

  • b和a都有键'a',但是b相对a,键'a'的值发生了变化,由原来的1,变为了2。所以在比较结果的list中,有一个元素反应了这个结果{'prev': 1, 'value': 2, 'replace': '/a'},其中,replace表示发生变化的键,value表示变化后即当前该键的值,prev表示该键此前的值。
  • b中的'c'相对与a,是新增的键。于是比较结果中这样反应出来:{'add': '/c', 'value': 2}
  • b相对于a没有'b'这个键,也就是在b中将其删除了,于是比较结果中这样来显示:{'prev': 2, 'remove': '/c'}

通过上述结果,就显示出来的详细的比较结果,不仅如此,还能对多层嵌套的json进行比较。例如:

>>> a={"a":{"aa":{"aaa":333,"aaa2":3332},"b":22}}
>>> b={"a":{"aa":{"aaa":334,"bbb":339},"b":22}}
>>> json_tools.diff(a,b)
[{'prev': 3332, 'remove': '/a/aa/aaa2'}, {'prev': 333, 'value': 334, 'replace': '/a/aa/aaa'}, {'add': '/a/aa/bbb', 'value': 339}]

这里就显明了发生变化的key的嵌套关系。比如'/a/aa/aaa2',就表示{"a":{"aa":{"aaa2":...}}}的值发生了变化。

这里有了一个key的嵌套字符串,在真实的使用中,有时候需要将字符串转为json的格式,即{'prev': 3332, 'remove': '/a/aa/aaa2'}转化为{"a":{"aa":{"aaa2":3332}}}

将字符串组装成json格式

首先,回答前面的问题,可以自己写一个函数,实现那种组装。

但是,我是懒惰地程序员,我更喜欢python的原因就是它允许我懒惰。

from itertools import izip

具体这个模块如何使用,请看官到我做过的一个小项目中看看:https://github.com/qiwsir/json-diff

results matching ""

    No results matching ""