Home > database >  Generate csv files from a JSON
Generate csv files from a JSON

Time:01-03

Unfortunately I have considerable difficulties to generate three csv files from one json format. Maybe someone has a good hint how I could do this. Thanks

Here is the output. Within dropped1 and dropped2 can be several different and multiple addresses.

{
  "result": {
    "found": 0,
    "dropped1": {
      "address10": 1140
    },
    "rates": {
      "total": {
        "1min": 3579,
        "5min": 1593,
        "15min": 5312,
        "60min": 1328
      },
      "dropped2": {
        "address20": {
          "1min": 9139,
          "5min": 8355,
          "15min": 2785,
          "60min": 8196
        }
      }
    },
    "connections": 1
  },
  "id": "whatever",
  "jsonrpc": "2.0"
}

The 3 csv files should be displayed in this form.

address10,1140

total,3579,1593,5312,1328

address20,9139,8355,2785,8196

CodePudding user response:

Did you try using this library? https://www.npmjs.com/package/json-to-csv-stream

npm i json-to-csv-stream

CodePudding user response:

If you decide to use jq, then unless there is some specific reason not to, I'd suggest invoking jq once for each of the three output files. The three invocations would then look like these:

jq -r '.result.dropped1 | [to_entries[][]] | @csv' > 1.csv

jq -r '.result.rates.total | ["total", .["1min"], .["5min"], .["15min"], .["60min"]] | @csv' > 2.csv

jq -r '.result.rates.dropped2.address20 | ["address20", .["1min"], .["5min"], .["15min"], .["60min"]] | @csv' > 3.csv

If you can be sure the ordering of keys within the total and address20 objects is fixed and in the correct order, then the last two invocations can be simplified.

  • Related