Convert a JSON into CSV using jq

2019-08-21 03:00发布

问题:

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

{ "users": [ { "username": "jack", "email": "jack@somewhere.com", "total running apps": "1", "api-mock-app": "0", "flogo": "1", "ipaas": "0", "nodejs-app": "0" }, { "username": "jill", "email": "jill@somewhere.com", "total running apps": "1", "api-mock-app": "0", "flogo": "1", "ipaas": "0", "nodejs-app": "0" } ] } When i am converting this JSON into CSV using this command

jq -r '.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv' <<< $temp

I am getting following error.

jq: error: syntax error, unexpected IDENT (Unix shell quoting issues?) at , line 1: .users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv
jq: 1 compile error

Any help Please?

回答1:

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'


回答2:

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



标签: json shell csv jq