使用jq或备用命令行工具比较JSON文件 [英] Using jq or alternative command line tools to compare JSON files

查看:115
本文介绍了使用jq或备用命令行工具比较JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Are there any command line utilities that can be used to find if two JSON files are identical with invariance to within-dictionary-key and within-list-element ordering?

这可以通过 jq 或其他等效工具来完成吗?

Could this be done with jq or some other equivalent tool?

这两个JSON文件是相同的

These two JSON files are identical

A:

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

B:

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

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

but these two JSON files are different:

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的比较已经在不考虑键顺序的情况下比较了对象,因此剩下的就是在比较对象之前对对象中的所有列表进行排序.假设您的两个文件在最新的jq每晚分别命名为a.jsonb.json:

Since jq's comparison already compares objects without taking into account key ordering, all that's left is to sort all lists inside the object before comparing them. Assuming your two files are named a.json and b.json, on the latest jq nightly:

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 program should return "true" or "false" depending on whether or not the objects are equal using the definition of equality you ask for.

在某些情况下,(.. | arrays) |= sort构造实际上无法按预期工作. 此GitHub问题解释了原因并提供了一些替代方法,例如:

The (.. | arrays) |= sort construct doesn't actually work as expected on some edge cases. This GitHub issue explains why and provides some alternatives, such as:

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

应用于上面的jq调用:

Applied to the jq invocation above:

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'

这篇关于使用jq或备用命令行工具比较JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆