2016-11-25 38 views
0

我有这个JSON文件:获取JSON文件中的最后一个元素

{ 
     "system.timestamp": "{system.timestamp}", 
     "error.state": "{error.state}", 
     "system.timestamp": "{system.timestamp}", 
     "error.state": "{error.state}", 
     "system.timestamp": "{system.timestamp}", 
     "error.state": "{error.state}", 
     "error.content": "{custom.error.content}" 
} 

我想只得到JSON文件的最后一个对象,我需要检查,在任何情况下,最后目标是error.content。代码的附加部分只是一个示例文件,实际生成的每个文件至少包含大约40到50个对象,因此在每种情况下,我都需要检查最后一个对象是否为error.content

我已经使用jq '. | length'计算了长度。我该如何在Linux中使用jq命令?

注意:这是一个普通的JSON文件,没有任何数组。

+1

这不是JSON ......好吧,从技术上讲,我想你可以说是的。但使用_many_重复键的对象实际上毫无价值。任何自尊的JSON解析器只会删除/覆盖重复的属性,并可能会保持最后。修复它比在该状态下尝试使用它更好。 –

回答

1

对象与使用--stream选项,如重复键可以在JQ进行处理:

$ jq -s --stream '.[length-2] | { (.[0][0]): (.[1]) }' input.json 
{ 
    "error.content": "{custom.error.content}" 
} 

对于大文件,以下可能会更好,因为它避免了“啜”输入文件:

$ jq 'first(tostream) | {(.[0][0]): .[1]} ' input.json 
相关问题