仅使用jq和bash将对象转换为数组

时间:2016-01-23 00:16:02

标签: json bash jq

我有一个JSON格式的流,充满了对象。每个对象如下所示:

{
  "object": "alpha",
  "attributes": [
    {
      "type": "A",
      "description": "a",
      "value": 1271129046.9144535
    },
    {
      "type": "B",
      "description": "b",
      "value": 6738889338.63777
    },
    {
      "type": "C",
      "description": "c",
      "value": 214918692.38456276
    },
    {
      "type": "D",
      "description": "d",
      "value": 140222346.75136077
    },
    {
      "type": "E",
      "description": "e",
      "value": 2085635554.8128803
    }
  ]
}

我希望将数据输出为:

alpha,A,a,1271129046.9144535
alpha,B,b,6738889338.63777
alpha,C,c,214918692.38456276
alpha,D,d,140222346.75136077
alpha,E,e,2085635554.8128803

下一个对象可能是“beta”而不是“alpha”,因此我不想只删除“对象”键。

我的限制是我想在bash管道中处理这个流。我希望我可以只使用“jq”,而不是通过python / ruby​​ / perl等管道,如果我能帮助它,我宁愿不依赖它。

任何想法都会非常感激!

2 个答案:

答案 0 :(得分:3)

看起来您正在构建CSV数据,@csv过滤器是为此而制作的。您只需要收集要写出的值的数组并将其传递给过滤器。你可以这样做:

$ jq -r '.attributes[] as $attr | [.object, $attr.type, $attr.description, $attr.value] | @csv' input.json

产生这个:

"alpha","A","a",1271129046.9144535
"alpha","B","b",6738889338.63777
"alpha","C","c",214918692.38456276
"alpha","D","d",140222346.75136077
"alpha","E","e",2085635554.8128803

答案 1 :(得分:0)

(1)比接受的答案稍微简短:

jq -r '[.object] + (.attributes[] | [.type, .description, .value]) | @csv'

(2)如果你不想要引号,那么一种可能性是:

jq -r '"\(.object)," + (.attributes[] | "\(.type),\(.description),\(.value)")'