[英]Parse json output using jq
Firstly,thank you so much for your support. 首先,非常感谢您的支持。
I have trouble parsing a json output into csv format. 我无法将json输出解析为csv格式。 I was able to get some kind of output but that does not meet the expectation.
我能够得到某种输出,但是不符合预期。
Curl Command output 卷曲命令输出
{
"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 used JQ commond二手
<curl-command>|jq '.results | map(.name), map(.DOB), map(.Enrollmentdate) | @csv' >file.csv
My Output 我的输出
smith jones, Jacob Mathew, Anita Rodrigues
1992-03-26, 1993-03-26, 1994-03-26
2013-08-24, 2014-10-02, 2015-02-19
This might not be csv exactly but below is the expected output. 这可能不完全是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
With your sample JSON, the invocation: 使用示例JSON,调用:
jq -r '
.results[]
| [.name, .DOB, .Enrollmentdate ]
| @csv'
produces: 产生:
"smith Jones","1992-03-26","2013-08-24"
"Jacob Mathew","1993-03-26","2014-10-02"
"Anita Rodrigues","1994-03-26","2015-02-19"
If you don't want the (in this case) superfluous quotation marks, you could replace @csv
by join(",")
but it would be better to write a simple filter to take care of values with commas, etc. 如果您不想(在这种情况下)多余的引号,可以用
join(",")
替换@csv
join(",")
但是最好编写一个简单的过滤器来处理逗号等值。
If the first result has the keys in the correct order, you could get away with: 如果第一个结果的键顺序正确,则可以避免:
(.results[0] | keys_unsorted),
(.results[]
| [.name, .DOB, .Enrollmentdate ])
| @csv
But it would probably be better to use a bit of jq magic along the lines of the following: 但是,按照以下方式使用jq魔术可能会更好:
(.results[0] | keys_unsorted) as $headers
| $headers,
(.results[]
| [getpath($headers[]|[.])])
| @csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.