Convert a JSON into CSV using jq

前端 未结 2 961
感动是毒
感动是毒 2021-01-27 12:49

I have a json file, which is stored in an environment variable temp.

{ \"users\": [ { \"username\": \"jack\", \"email\": \"jack@somewhere.com\",

相关标签:
2条回答
  • 2021-01-27 12:53

    i got this working code click here

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <html>
    <head>
        <title>Demo - Covnert JSON to CSV</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
    
        <script type="text/javascript">
            // JSON to CSV Converter
            function ConvertToCSV(objArray) {
                var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
                var str = '';
    
                for (var i = 0; i < array.length; i++) {
                    var line = '';
                    for (var index in array[i]) {
                        if (line != '') line += ','
    
                        line += array[i][index];
                    }
    
                    str += line + '\r\n';
                }
    
                return str;
            }
    
            // Example
            $(document).ready(function () {
    
                // Create Object
                var items = [
                      { name: "Item 1", color: "Green", size: "X-Large" },
                      { name: "Item 2", color: "Green", size: "X-Large" },
                      { name: "Item 3", color: "Green", size: "X-Large" }];
    
                // Convert Object to JSON
                var jsonObject = JSON.stringify(items);
    
                // Display JSON
                $('#json').text(jsonObject);
    
                // Convert JSON to CSV & Display CSV
                $('#csv').text(ConvertToCSV(jsonObject));
            });
        </script>
    </head>
    <body>
        <h1>
            JSON</h1>
        <pre id="json"></pre>
        <h1>
            CSV</h1>
        <pre id="csv"></pre>
    </body>
    </html>

    check out this link

    0 讨论(0)
  • 2021-01-27 13:15

    You need to quote your column names, especially since they contain spaces and dashes. However you need to escape the quotes for bash:

    jq --raw-output '.users[] | [.username, .email, ."total running apps", ."api-mock-app", ."flogo", ."ipaas", ."nodejs-app"] | @csv'
    
    0 讨论(0)
提交回复
热议问题