Convert .json to .csv in ruby

前端 未结 7 1412
心在旅途
心在旅途 2020-12-24 09:42

I want to convert .json file into .csv file using ruby. Pleases help me to do this.

Also propose any tool to achieve this.

相关标签:
7条回答
  • 2020-12-24 10:11

    I think the easies way to convert the JSON to CSV in ruby is using json2csv ruby gem.

    PS: I may be biased as I am author of this.

    json2csv github repo

    Running the command

    json2csv convert data/sample.json
    

    Input File

    In this particular case it will convert following json:

    cat data/sample.json
    
    {
        "12345": {
            "Firstname": "Joe",
            "Lastname": "Doe",
            "Address": {
                "Street": "#2140 Taylor Street, 94133",
                "City": "San Francisco",
                "Details": {
                    "note": "Pool available"
                }
            }
        },
    
        "45678": {
            "Firstname": "Jack",
            "Lastname": "Plumber",
            "Address": {
                "Street": "#111 Sutter St, 94104",
                "City": "San Francisco",
                "Details": {
                    "note": "Korean Deli near to main entrance"
                }
            }
        }
    }
    

    Output

    cat data/sample.json.csv
    
    id,Firstname,Lastname,Address.Street,Address.City,Address.Details.note
    12345,Joe,Doe,"#2140 Taylor Street, 94133",San Francisco,Pool available
    45678,Jack,Plumber,"#111 Sutter St, 94104",San Francisco,Korean Deli near to main entrance
    
    0 讨论(0)
提交回复
热议问题