mrodrig / json-2-csv

Convert JSON to CSV *or* CSV to JSON!
https://mrodrig.github.io/json-2-csv
MIT License
424 stars 58 forks source link

csv2json --select "path.to.object" to export only object #261

Open porg opened 3 months ago

porg commented 3 months ago

Foreword

User Story

From a large JSON file containing a lot of stuff I want the option to select only a particular object for export to CSV.

With a syntax like --select "path.to.object"

Or another argument name you deem appropriate as the mnemonics -s and -S are both already taken.

Given example.json

{
  "version": "1.5",
  "global_option_a": "something",
  "global_option_b": "else",
  "global_option_c": 123,
  "people": [
    {
      "firstname": "Jon",
      "lastname": "Doe",
      "birthday": "1978-02-19",
      "gender": "m"
    },
    {
      "firstname": "Jane",
      "lastname": "Doe",
      "birthday": "1982-04-21",
      "gender": "f"
    },
    {
      "firstname": "Dave",
      "lastname": "Meyer",
      "birthday": "1964-12-03",
      "gender": "m"
    }
  ],
  "locations": {
    "Europe": [
      {
        "ID": "1",
        "Name": "London"
      },
      {
        "ID": "2",
        "Name": "Paris"
      },
      {
        "ID": "3",
        "Name": "Madrid"
      }
    ],
    "Asia": [
      {
        "ID": "4",
        "Name": "Tokio"
      },
      {
        "ID": "5",
        "Name": "Seoul"
      }
    ]
  }
}

To get people.csv I'd run…

$ json2csv example.json --select "people" > people.csv

which results in:

firstname,lastname,birthday,gender
Jon,Doe,1978-02-19,m
Jane,Doe,1982-04-21,f
Dave,Mayer,1964-12-03,m

To get locations-asia.csv I'd run

$ json2csv example.json --select "locations.Asia" > locations-asia.csv

which results in:

ID,Name
4,Tokio
5,Seoul
porg commented 3 months ago

On my second read of the manpage I realized that --keys is probably getting close to what I need. But still I cannot achieve my desired goal. I'm doing something wrong it seems:


$ json2csv example.json --keys people   
people
"[{""firstname"":""Jon"",""lastname"":""Doe"",""birthday"":""1978-02-19"",""gender"":""m""},{""firstname"":""Jane"",""lastname"":""Doe"",""birthday"":""1982-04-21"",""gender"":""f""},{""firstname"":""Dave"",""lastname"":""Meyer"",""birthday"":""1964-12-03"",""gender"":""m""}]"

$ json2csv example.json --keys people --unwind-arrays
people
"{""firstname"":""Jon"",""lastname"":""Doe"",""birthday"":""1978-02-19"",""gender"":""m""}"
"{""firstname"":""Jane"",""lastname"":""Doe"",""birthday"":""1982-04-21"",""gender"":""f""}"
"{""firstname"":""Dave"",""lastname"":""Meyer"",""birthday"":""1964-12-03"",""gender"":""m""}"

So yes, I'm out of wits. Looking forward to your reaction!

porg commented 2 months ago

@mrodrig any input? Would be appreciated! Thanks!