简体   繁体   English

使用jq从json获取父值

[英]Get parent value from json using jq

My json file looks like this; 我的json文件看起来像这样;

{
 "RQBTYFE86MFC3oL": {
    "name": "Nightmode",
    "lights": [
      "1",
      "2",
      "3",
      "4",
      "5",
      "7",
      "8",
      "9",
      "10",
      "11"
    ],
    "owner": "kvovodUUfn2vlby9h9okdDhv8SrTzkBFjk6kPz2v",
    "recycle": false,
    "locked": false,
    "appdata": {
      "version": 1,
      "data": "QSXCj_r01_d99"
    },
    "picture": "",
    "lastupdated": "2018-08-08T03:21:39",
    "version": 2
  }
}

I want to get the 'RQBTYFE86MFC3oL' value by doing a query for 'Nightmode'. 我想通过查询“ Nightmode”来获取“ RQBTYFE86MFC3oL”值。 So far I came up with this; 到目前为止,我想到了这个。

jq '.[] | select(.name == "Nightmode")'

This will return me the correct part of the Json but the 'RQBTYFE86MFC3oL' part is stripped. 这将为我返回Json的正确部分,但是'RQBTYFE86MFC3oL'部分被剥去了。 How do I get this part as well? 我也该如何获得这部分?

A simple way to determine the key name(s) corresponding to values satisfying a certain condition is to use to_entries , as explained in the jq manual. 确定与满足特定条件的值相对应的键名的一种简单方法是使用to_entries ,如jq手册中所述。

Using this approach, the appropriate jq filter would be: 使用这种方法,合适的jq过滤器将是:

to_entries[] | select(.value.name == "Nightmode") | .key 

with the result: 结果:

"RQBTYFE86MFC3oL"

If you want to get the key-value pair, you'd use with_entries as follows: 如果要获取键值对,请按以下方式使用with_entries

with_entries( select(.value.name == "Nightmode") )

If the input JSON is too large to fit comfortably in memory, then it would make sense to use jq's streaming parser (invoked with the --stream command-line option): 如果输入的JSON太大而无法舒适地容纳在内存中,则使用jq的流解析器(通过--stream命令行选项调用)是有意义的:

jq --stream '
  select(.[1] == "Nightmode" and (first|length) == 2 and first[1] == "name")
  | first | first' 

This would produce the key name. 这将产生密钥名称。

The key idea is that the streaming parser produces arrays including pairs of the form: [ARRAYPATH, VALUE] where VALUE is the value at ARRAYPATH. 关键思想是流解析器生成的数组包括以下形式的对:[ARRAYPATH,VALUE]其中VALUE是ARRAYPATH上的值。

You want to get the Key Value. 您想获取键值。

So use the keys command, to return 'RQBTYFE86MFC3oL' as that is the key, the rest is the value of that key. 因此,请使用keys命令,返回“ RQBTYFE86MFC3oL”,因为这是键,其余部分是该键的值。

jq 'keys'

Here is a snippet: https://jqplay.org/s/YvpCb2PH42 这是一个代码段: https : //jqplay.org/s/YvpCb2PH42

Reference: https://stedolan.github.io/jq/manual/ 参考: https : //stedolan.github.io/jq/manual/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM