简体   繁体   English

jq基于键值过滤器查询json键

[英]jq query json key based on key value filter

I have a json file with key and the value is a json with key value pair. 我有一个带键的json文件,值是带键值对的json。 I would like to filter and extract the key based on the inner key value pair. 我想根据内部键值对过滤并提取键。 Any help is greatly appreciated 任何帮助是极大的赞赏

Example json data: 示例json数据:

{
    "key1": {
      "filterkey": "filtervalue",
      "key1": "value1"
    },
    "key2": {
      "key1": "value1",
      "key2": "value2"
    }
}
  • Filter: "filterkey": "filtervalue" 过滤器:“ filterkey”:“ filtervalue”
  • expected output: "key1" 预期输出:“ key1”

if your input json is stable and you do not need to control any edge cases (arbitrary depth, a top-level type mismatch, eg "key1": "not a dict" ) then this solves your problem: 如果您输入的json是稳定的,并且您不需要控制任何边缘情况(任意深度,顶级类型不匹配,例如"key1": "not a dict" ),那么这可以解决您的问题:

ret = []
for k, v in js.items():
    if v.get("filterkey") == "filtervalue":
        ret.append(k)

Run snippet to see output: 运行代码片段以查看输出:

  var jsonObject = { "key1": { "filterkey": "filtervalue", "key1": "value1" }, "key2": { "key1": "value1", "key2": "value2" } }; function filterKey(jsonObject, keySearch, valueSearch) { var result = null; for (const key in jsonObject) { if (jsonObject.hasOwnProperty(key) && jsonObject[key][keySearch] !== undefined && jsonObject[key][keySearch] === valueSearch) { result = key; break; } } return result; } alert(filterKey(jsonObject, 'filterkey', 'filtervalue')); 

jq '.[] | select( .filterkey == "filtervalue") | to_entries[1]| .key'   sample.json

Select by filterkey, turn the objects into key value entires, then take the second entry's key. 通过filterkey选择,将对象变成整个键值,然后使用第二个条目的键。 Output is: 输出为:

"key1"

In the example, "key1" appears several times, but it looks like you want the outermost key name. 在该示例中,“ key1”出现了几次,但看起来您想要最外层的键名。 If that's the case, then using to_entries is a good way to go, eg: 如果是这样,那么使用to_entries是一个好方法,例如:

to_entries[]
| if .value.filterkey == "filtervalue" then .key else empty end

Or equivalently: 或等效地:

to_entries[]
| select(.value.filterkey == "filtervalue" )
| .key

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

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