使用jq解析json输出

时间:2019-08-15 02:27:09

标签: json export-to-csv jq

首先,非常感谢您的支持。

我无法将json输出解析为csv格式。我能够获得某种输出,但是不符合预期。

卷曲命令输出

{
    "results": [{
            "name": "smith Jones",
            "DOB": "1992-03-26",
            "Enrollmentdate": "2013-08-24"

        },

        {
            "name": "Jacob Mathew",
            "DOB": "1993-03-26",
            "Enrollmentdate": "2014-10-02"
        },

        {
            "name": "Anita Rodrigues",
            "DOB": "1994-03-26",
            "Enrollmentdate": "2015-02-19"
        }
    ]
}

使用了JQ commond

<curl-command>|jq '.results | map(.name), map(.DOB), map(.Enrollmentdate) | @csv' >file.csv

我的输出

smith jones, Jacob Mathew, Anita Rodrigues
1992-03-26, 1993-03-26, 1994-03-26
2013-08-24, 2014-10-02, 2015-02-19 

这可能不完全是csv,但低于预期的输出。

Name                 DOB             Enrollmentdate
smith jones,       1992-03-26,        2013-08-24
jacob Mathew,      1993-03-26,        2014-10-02
Anitha Rodrigues,  1994-03-26,        2015-02-19

1 个答案:

答案 0 :(得分:2)

使用示例JSON,调用:

list1 =  [{'NY':(80, 'EQ'),'FL':(30, 'FI'), 'IL':(60, 'AI')}, {'NY':(90, 'EQ'), 'GA':(10, 'RE'), 'CA':(20, 'HA')}] 

产生:

jq -r '
  .results[]
  | [.name, .DOB, .Enrollmentdate ]
  | @csv'

如果您不想(在这种情况下)多余的引号,可以将"smith Jones","1992-03-26","2013-08-24" "Jacob Mathew","1993-03-26","2014-10-02" "Anita Rodrigues","1994-03-26","2015-02-19" 替换为@csv,但是最好编写一个简单的过滤器以逗号分隔值等

标题

如果第一个结果具有正确顺序的键,则可以避免使用

join(",")

但是,最好按照以下方式使用一些jq魔术:

  (.results[0] | keys_unsorted),
  (.results[]
  | [.name, .DOB, .Enrollmentdate ])
  | @csv