Converting CSV to JSON in bash

前端 未结 9 1875
梦毁少年i
梦毁少年i 2021-02-04 03:12

Trying to convert a CSV file into a JSON

Here is two sample lines :

-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata
         


        
9条回答
  •  一整个雨季
    2021-02-04 03:37

    The accepted answer uses jq to parse the input. This works but jq doesn't handle escapes i.e. input from a CSV produced from Excel or similar tools is quoted like this:

    foo,"bar,baz",gaz
    

    will result in the incorrect output, as jq will see 4 fields, not 3.

    One option is to use tab-separated values instead of comma (as long as your input data doesn't contain tabs!), along with the accepted answer.

    Another option is to combine your tools, and use the best tool for each part: a CSV parser for reading the input and turning it into JSON, and jq for transforming the JSON into the target format.

    The python-based csvkit will intelligently parse the CSV, and comes with a tool csvjson which will do a much better job of turning the CSV into JSON. This can then be piped through jq to convert the flat JSON output by csvkit into the target form.

    With the data provided by the OP, for the desired output, this as as simple as:

    csvjson --no-header-row  |
      jq '.[] | {occurrences: [{ position: [.a, .b], taxo: {espece: .c}}]}'
    

    Note that csvjson automatically detects ; as the delimiter, and without a header row in the input, assigns the json keys as a, b, and c.

    The same also applies to writing to CSV files -- csvkit can read a JSON array or new-line delimited JSON, and intelligently output a CSV via in2csv.

提交回复
热议问题