Home > Software design >  duplicate headers after convert to csv
duplicate headers after convert to csv

Time:01-30

In json file:

{
  "issues": [
    {
      "key": "key_1",
      "component": "my_component",
      "textRange": {
        "startLine": 1,
        "endLine": 11,
        "startOffset": 111,
        "endOffset": 1111
      }
    },
    {
      "key": "key2",
      "component": "my component 2",
      "textRange": {
        "startLine": 2,
        "endLine": 22,
        "startOffset": 222,
        "endOffset": 2222
      }
    },
    {
      "key": "my_key3",
      "component": "my component 3",
      "textRange": {
        "startLine": 548,
        "endLine": 548,
        "startOffset": 14,
        "endOffset": 15
      }
    }
  ]
}

I want to convert to csv and add headers.

I try this:

jq -r '.issues[] | ["key","component", "textRange"], [.key,.component, .textRange[]] | @csv' test.issues.json

Result:

"key","component","textRange"
"key_1","my_component",1,11,111,1111
"key","component","textRange"
"key2","my component 2",2,22,222,2222
"key","component","textRange"
"my_key3","my component 3",548,548,14,15

Why headers are duplicate?

CodePudding user response:

You are creating the headers inside the iteration. Pull them up front

["key","component", "textRange"],
(.issues[] | [.key,.component, .textRange[]])
| @csv
"key","component","textRange"
"key_1","my_component",1,11,111,1111
"key2","my component 2",2,22,222,2222
"my_key3","my component 3",548,548,14,15

Demo

  •  Tags:  
  • Related