jq - 如何遍历不同名称的键

jq - How to iterate through keys of different names

我有 JSON 看起来像这样

{
  "keyword1": {
    "identifier1": 16
  },
  "keyword2": {
    "identifier2": 16
  }
}

我需要遍历关键字来获取标识符(不确定我在这里使用的术语是否正确)。看起来很简单,但是因为关键字的命名都不一样,不知道怎么处理。

这个问题的原始标签是 jq 所以这是一个 jq 解决方案:

.[] | keys[]

例如,输入如问题所示:

$ jq '.[] | keys[]' input.json

"identifier1"
"identifier2"

要按照键名称在 JSON 对象中出现的顺序检索键名称,请使用 keys_unsorted.

我来这里是想从我的 JSON 中整理出一堆钥匙,我发现有两个功能很方便。共有"to_entries"、"from_entries"、"with_entries"三个函数。您可以按键或值过滤值,如下所示:

JSON_DATA='
{
  "fields": {
    "first": null,
    "second": "two",
    "third": "three"
  }
}
'

echo "$JSON_DATA" | jq '{fields: .fields | with_entries(select(.value != null and .key != "third")) }'

输出:

{
  "fields": {
    "second": "two"
  }
}

我认为按照这些思路行事会很好:

jq '. | to_entries | .[].key'

https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries

或者如果您想从变量中获取值:

JSON_DATA={main:{k1:v1,k2:v2}}
result=$(jq -n "$JSON_DATA" | jq '.main | to_entries | .[].value' --raw-output)
echo $result

##outputs: v1 v2