安装
pip install json_tools
使用
输出导读:
上面的输出显示的是b相对于a的变化:
1) b和a都有键’rd’,但是b相对a键’rd’的值发生了变化,由原来的yanan变为Yanan,所以比较结果的list有{“replace”: “/rd”, “value“: “Yanan”, “prev”: “yanan”}
其中replace标识发生变化的键,value标识变化后即当前该键的值,prev表示该键此前的值。
2) b相对于a没有city键,所以结果集中有{“remove”: “/city”, “prev”: “zibo”}
3) b中的town相对于a,是新增的键,所以结果集中有{“add”: “/town”, “value”: “taian”}
多层嵌套的对比
<span style="font-size: 14px"><span>import</span><span> json_tools </span><span>def</span><span> json_diff(json_1, json_2): result </span>=<span> json_tools.diff(json_1, json_2) </span><span>print</span><span>(result) a </span>= {<span>"</span><span>rd</span><span>"</span>: <span>"</span><span>yanan</span><span>"</span>, <span>"</span><span>pro</span><span>"</span>: {<span>"</span><span>sh</span><span>"</span>: <span>"</span><span>shandong</span><span>"</span>, <span>"</span><span>city</span><span>"</span>: [<span>"</span><span>zibo</span><span>"</span>, <span>"</span><span>weifang</span><span>"</span><span>]}} b </span>= {<span>"</span><span>rd</span><span>"</span>: <span>"</span><span>Yanan</span><span>"</span>, <span>"</span><span>pro</span><span>"</span>: {<span>"</span><span>sh</span><span>"</span>: <span>"</span><span>shandong</span><span>"</span>, <span>"</span><span>town</span><span>"</span>: [<span>"</span><span>taian</span><span>"</span>, <span>"</span><span>weifang</span><span>"</span><span>]}} json_diff(a, b)</span></span>
www#gaodaima.com来源gaodai#ma#com搞@代~码网搞代码
结果:
[{<span>"</span><span>replace</span><span>"</span>: <span>"</span><span>/rd</span><span>"</span>, <span>"</span><span>value</span><span>"</span>: <span>"</span><span>Yanan</span><span>"</span>, <span>"</span><span>prev</span><span>"</span>: <span>"</span><span>yanan</span><span>"</span>}, <br>{<span>"</span><span>remove</span><span>"</span>: <span>"</span><span>/pro/city</span><span>"</span>, <span>"</span><span>prev</span><span>"</span>: [<span>"</span><span>zibo</span><span>"</span>, <span>"</span><span>weifang</span><span>"</span>]}, <br>{<span>"</span><span>add</span><span>"</span>: <span>"</span><span>/pro/town</span><span>"</span>, <span>"</span><span>value</span><span>"</span>: [<span>"</span><span>taian</span><span>"</span>, <span>"</span><span>weifang</span><span>"</span>]}]