Home > Software design >  How to convert specific JSON file to CSV
How to convert specific JSON file to CSV

Time:12-14

Here is my sample.json:

  {
    "process" : {
      "pid" : "1462",
      "path" : "\/Applications\/Google Chrome.app\/Contents\/Frameworks\/Google Chrome Framework.framework\/Versions\/108.0.5359.98\/Helpers\/Google Chrome Helper.app\/Contents\/MacOS\/Google Chrome Helper",
      "signature(s)" : {
        "signatureIdentifier" : "com.google.Chrome.helper",
        "signatureStatus" : 0,
        "signatureSigner" : 3,
        "signatureAuthorities" : [
          "Developer ID Application: Google LLC (EQHXZ8M8AV)",
          "Developer ID Certification Authority",
          "Apple Root CA"
        ]
      }
    },
    "connections" : [
      {
        "remoteHostName" : "n\/a",
        "protocol" : "UDP",
        "interface" : "",
        "localAddress" : "::",
        "state" : "n\/a",
        "remotePort" : "0",
        "localPort" : "5353",
        "remoteAddress" : "::"
      },
      {
        "remoteHostName" : "n\/a",
        "protocol" : "TCP",
        "interface" : "en0",
        "localAddress" : "2a02:560:5424:b200:359c:f801:abab:cd28",
        "state" : "Established",
        "remotePort" : "443",
        "localPort" : "50190",
        "remoteAddress" : "2600:1f18:60d5:4e03:ffe8:813e:6d1a:d379"
      }
    ]
  }

I would like to create a custom CSV from this data to see all connections by process id (pid), but I don't get it.

What I have so far:

cat sample.json | jq '[.process.pid], (.connections | .[])'

Thanks in advance for your help!

CodePudding user response:

jq -r '{pid: .process.pid}   .connections[] | to_entries | map(.value) | @csv' input.json

Output

"1462","n/a","UDP","","::","n/a","0","5353","::"
"1462","n/a","TCP","en0","2a02:560:5424:b200:359c:f801:abab:cd28","Established","443","50190","2600:1f18:60d5:4e03:ffe8:813e:6d1a:d379"
  • Related