【问题标题】:Get list of values for each unique key of json with jq使用 jq 获取 json 的每个唯一键的值列表
【发布时间】:2021-10-18 18:54:44
【问题描述】:

伙计们。任务是:获取所有唯一键和这些键的匹配值列表,然后将它们包装在 {}

json 看起来像:

{
    "sepalLength": 5,
    "sepalWidth": 3.3,
    "petalLength": 1.4,
    "petalWidth": 0.2,
    "species": "setosa"
  },
  {
    "sepalLength": 7,
    "sepalWidth": 3.2,
    "petalLength": 4.7,
    "petalWidth": 1.4,
    "species": "versicolor"
  },
  {
    "sepalLength": 6.4,
    "sepalWidth": 3.2,
    "petalLength": 4.5,
    "petalWidth": 1.5,
    "species": "versicolor"
  },
...

结果必须是这样的:

{
    "species": ["setosa", "setosa", ...],
    "petalWidth": [1.2, ...],
    ...
}

【问题讨论】:

  • 您尝试过什么? idownvotedbecau.se/noattempt
  • 哦,对不起,我是新来的,我不知道这个规则。我试过这个:jq'。作为 $glob | foreach [[.[] |键[]] | unique[]][] as $item (0; .+1; "(.) - ($glob[$item])")' iris.json 但是发生了错误。我以前没用过jq,所以犯了愚蠢的错误)
  • 无铅。欢迎来到 SO。下次,编辑您的问题以显示代码,不要放在评论中。

标签: json jq


【解决方案1】:

假设你的输入数据是一个数组

[
  {
    "sepalLength": 5,
    "sepalWidth": 3.3,
    "petalLength": 1.4,
    "petalWidth": 0.2,
    "species": "setosa"
  },
  {
    "sepalLength": 7,
    "sepalWidth": 3.2,
    "petalLength": 4.7,
    "petalWidth": 1.4,
    "species": "versicolor"
  },
  ...
]

以下

jq '[(map(keys[]) | unique[]) as $key | {($key): map(.[$key])} ] | add'

如果输入你的样本数据会产生类似的东西

{
  "petalLength": [1.4,4.7,4.5],
  "petalWidth": [0.2,1.4,1.5],
  "sepalLength": [5,7,6.4],
  "sepalWidth": [3.3,3.2,3.2],
  "species": ["setosa","versicolor","versicolor"]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2017-02-09
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多