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

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

内容简介:代码日志版权声明:翻译自: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


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

查看所有标签

猜你喜欢:

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

Ethnography and Virtual Worlds

Ethnography and Virtual Worlds

Tom Boellstorff、Bonnie Nardi、Celia Pearce、T. L. Taylor / Princeton University Press / 2012-9-16 / GBP 21.00

"Ethnography and Virtual Worlds" is the only book of its kind - a concise, comprehensive, and practical guide for students, teachers, designers, and scholars interested in using ethnographic methods t......一起来看看 《Ethnography and Virtual Worlds》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具