使用jq或替代命令行工具来区分JSON文件

栏目: 后端 · 前端 · 发布时间: 6年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/31930041/using-jq-or-alternative-command-line-tools-to-diff-json-files

是否有任何命令行实用程序可用于查找两个JSON文件是否与字典内键和列表内元素 排序 中的不变性相同?

这可以用 jq 还是其他一些等效的工具?

例子:

这两个JSON文件是相同的

A:
{
  "People": ["John", "Bryan"],
  "City": "Boston",
  "State": "MA"
}

B:
{
  "People": ["Bryan", "John"],
  "State": "MA",
  "City": "Boston"
}

但是这两个JSON文件是不同的:

A:
{
  "People": ["John", "Bryan", "Carla"],
  "City": "Boston",
  "State": "MA"
}

C:
{
  "People": ["Bryan", "John"],
  "State": "MA",
  "City": "Boston"
}

那将是:

$some_diff_command A.json B.json

$some_diff_command A.json C.json
The files are not structurally identical

由于jq的比较已经比较了对象而不考虑密钥排序,所有剩下的都是在比较对象之前对对象内的所有列表进行排序.假设你的两个文件被命名为a.json和b.json,在最新的jq每晚:

jq --argfile a a.json --argfile b b.json -n '($a | (.. | arrays) |= sort) as $a | ($b | (.. | arrays) |= sort) as $b | $a == $b'

该程序应该返回“true”或“false”,这取决于对象是否相等,使用您要求的等式的定义.

编辑:(.. |数组)| =排序构造在某些边缘情况下实际上并不按预期工作. This GitHub issue 解释了为什么并提供了一些替代方案,如:

def post_recurse(f): def r: (f | select(. != null) | r), .; r; def post_recurse: post_recurse(.[]?); (post_recurse | arrays) |= sort

适用于上面的jq调用:

jq --argfile a a.json --argfile b b.json -n 'def post_recurse(f): def r: (f | select(. != null) | r), .; r; def post_recurse: post_recurse(.[]?); ($a | (post_recurse | arrays) |= sort) as $a | ($b | (post_recurse | arrays) |= sort) as $b | $a == $b'

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/31930041/using-jq-or-alternative-command-line-tools-to-diff-json-files


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mastering Bitcoin

Mastering Bitcoin

Andreas M. Antonopoulos / O'Reilly Media / 2014-12-20 / USD 34.99

Mastering Bitcoin tells you everything you need to know about joining one of the most exciting revolutions since the invention of the web: digital money. Bitcoin is the first successful digital curren......一起来看看 《Mastering Bitcoin》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换