arrays - jq - 将对象列表转换为汇总对象

标签 arrays json jq

我有这样的 JSON 数据:

[
  {
    "tone_id": "anger",
    "score": 0.012,
    "tone_name": "Anger"
  },
  {
    "tone_id": "disgust",
    "score": 0.002,
    "tone_name": "Disgust"
  },
  {
    "tone_id": "fear",
    "score": 0.14,
    "tone_name": "Fear"
  },
  {
    "tone_id": "joy",
    "score": 0.42,
    "tone_name": "Joy"
  }
]

我想使用 将其转换为以下内容jq :
{
  "anger": 0.012,
  "disgust": 0.002,
  "fear": 0.14,
  "joy": 0.42
}

我能做的最好的是:
cat result.json | jq '.[] | { (.tone_id): .score }'

这给出了以下内容:
{
  "anger": 0.012
}
{
  "disgust": 0.002
}
{
  "fear": 0.14
}
{
  "joy": 0.42
}

I know I can easily do this using other methods. Just wanted to know if it's possible using jq one-liner?

最佳答案

单次调用单行:

 jq 'map( {(.tone_id): .score} ) | add'

(你也可以在传递给 .[] | { (.tone_id): .score } 之前用方括号包裹 add——这两种方法是等价的。)

关于arrays - jq - 将对象列表转换为汇总对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551333/

相关文章:

json - 通过 JQ 将纯文本文件导入 JSON

python - 错误的 JSON 到自定义 JSON

c - 在 C 中对整数数组进行冒泡函数排序

python - 使用 numpy genfromtxt 读取每第 n 行的最快方法

Python 3 将 json 值读取为元组

javascript - 如何使用 AngularJs 过滤 JSON 数据

javascript - 从浏览器写入本地 JSON 文件

json - 如何使用jq从数组中的每个对象中提取字段?

javascript - 对嵌套的对象数组进行分组

php - 更改日期格式,来自 postgresql 的 php echo 总是返回 "Date(1970, 01, 01)"