简体   繁体   English

如何使用jq将来自不同JSON对象的值合并到一行CSV

[英]How to combine values from different JSON objects to one line of CSV using jq

I want to extract data from a JSON file and write it to a CSV file using . 我想从JSON文件中提取数据,然后使用将其写入CSV文件。

This is a sample of my data: 这是我的数据样本:

[
  {
    "media": {
      "track": [
        {
          "attype": "General",
          "FileExtension": "MP4",
          "Format": "MPEG-4"
        },
        {
          "attype": "Video",
          "Format": "MPEG Video"
        }
      ]
    }
  },
  {
    "media": {
      "track": [
        {
          "attype": "General",
          "FileExtension": "ts",
          "Format": "MPEG-TS"
        },
        {
          "attype": "Video",
          "Format": "MPEG Video"
        }
      ]
    }
  }
]

This is the desired output: 这是所需的输出:

"MP4","MPEG-4","MPEG Video"
"ts","MPEG-TS","MPEG Video"

This is my code: 这是我的代码:

.[].media.track[] |
  [
    (select(.attype =="General") | .FileExtension, .Format),
    (select(.attype =="Video") | .Format)
  ] | @csv

This is the actual output: 这是实际输出:

"MP4","MPEG-4"
"MPEG Video"
"ts","MPEG-TS"
"MPEG Video"

I have experimented with the flatten filter and with different usage of the square brackets [] for array construction, but to no avail. 我已经试验过flatten滤波器和方括号[]用于数组构造的不同用法,但无济于事。 How can I reach the desired output with ? 如何使用达到所需的输出?

You're on the right track (pun intended) -- you just have to expand .track as follows: 您处在正确的轨道上(按双关语)–您只需按以下方式扩展.track即可:

.[].media.track
| [.[]
   | (select(.attype =="General") | .FileExtension, .Format),
     (select(.attype =="Video") | .Format) ]
| @csv

Alternatively ... 或者...

If you find all those brackets and parentheses to be too distracting, you could go with: 如果您发现所有这些括号和括号过于分散注意力,则可以采用:

.[].media.track
| map( if .attype =="General" then .FileExtension, .Format
       elif .attype =="Video" then .Format
       else empty
       end )
| @csv

A solution is to create a cells array for each media rather than for each track : 一个解决方案是为每个媒体而不是每个轨道创建一个单元格数组:

.[].media | 
  [ 
    .track[] |
       (select(.attype =="General") | .FileExtension, .Format),
       (select(.attype =="Video") | .Format)
  ] | @csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM