使用jq

时间:2017-11-21 12:10:04

标签: json jq

我尝试将嵌套对象和数组的JSON转换为CSV文件。结构是:

{
  "Date": {
    "Value": "2017-11-17T00:00:00"
  },
  "ThisOne": false
}
{
  "Date": {
    "Value": "2017-11-17T00:00:00"
  },
  "ThisOne": true,
  "Groups": {
    "10": {
      "Id": "10",
      "SomeUnnecessaryObject": true
    },
    "11": {
      "Id": "11",
      "RequiredObject": {
        "SEeminGlyRANdOMStRiNG": {
          "Value1": "2",
          "Value2": "3",
          "Units": [
            "1",
            "5"
          ]
        }
      }
    },
    "12": {
      "Id": "12",
      "RequiredObject": {
        "AnOthEr321": {
          "Value1": "1",
          "Value2": "9",
          "Units": [
            "2"
          ]
        }
      }
    }
  }
}

(希望我的括号正确)并且我试图将其转换为csv:

date|value1|value2|group|unit1|unit2|unit3|unit4|unit5
2017-11-17T00:00:00|2|3|11|1|0|0|0|1
2017-11-17T00:00:00|1|9|12|0|1|0|0|0

组从10到99,单位从1到5. SEeminGlyRANdOMStRiNG是一个看似随机的字符串。我想要的对象有RequiredObject,但有顶级对象没有它。我已经使用select(.ThisOne==true)修剪了对象,因为我不了解如何从.Group ... RequiredObject ... Value1引用路径中不断变化的值。可能有顶级对象ThisOne==true但缺少RequiredObject s。

1 个答案:

答案 0 :(得分:2)

假设您在单位列as in your earlier question上具有相同的条件,则以下过滤器应生成所需的输出:

  ["\(1+range(5))"] as $units
| ["date", "value1", "value2", "group", "unit\($units[])"]
, (
      inputs
    | .Date.Value as $date
    | .Groups[]?
    | .Id as $group
    | .RequiredObject // {}
    | keys[] as $k
    | .[$k]
    | .Value1 as $value1
    | .Value2 as $value2
    | [ $date, $value1, $value2, $group, (.Units[$units[]|[.]] | if .!=[] then "1" else "0" end) ]
  )
| join("|")

示例运行(假定filter.jq中的过滤器和data.json中的数据)

$ jq -Mnr -f filter.jq data.json
date|value1|value2|group|unit1|unit2|unit3|unit4|unit5
2017-11-17T00:00:00|2|3|11|1|0|0|0|1
2017-11-17T00:00:00|1|9|12|0|1|0|0|0

Try it online!