如何使用jq将json转换为csv文件? [英] How to convert json into csv file using jq?
问题描述
这是我的json文件:
This is my json file:
{
"ClientCountry": "ca",
"ClientASN": 812,
"CacheResponseStatus": 404,
"CacheResponseBytes": 130756,
"CacheCacheStatus": "hit"
}
{
"ClientCountry": "ua",
"ClientASN": 206996,
"CacheResponseStatus": 301,
"CacheResponseBytes": 142,
"CacheCacheStatus": "unknown"
}
{
"ClientCountry": "ua",
"ClientASN": 206996,
"CacheResponseStatus": 0,
"CacheResponseBytes": 0,
"CacheCacheStatus": "unknown"
}
我想将这些json转换为csv,如下所示.
I want to convert these json into csv like below.
"ClientCountry", "ClientASN","CacheResponseStatus", "CacheResponseBytes", "CacheCacheStatus"
"ca", 812, 404, 130756, "hit";
"ua", 206996, 301, 142,"unknown";
"ua", 206996, 0,0,"unknown";
请让我知道如何使用jq实现这一目标?
Please let me know how to achieve this using jq?
我只是在下面尝试过.但它不起作用.
I just tried below. But its not working.
jq 'to_entries[] | [.key, .value] | @csv'
问候 帕拉尼
推荐答案
由于您需要所有键值, 然后假设键在输入文件中以一致的顺序显示,您可以简单地编写:
Since you want all the key-values, then assuming that the keys are presented in a consistent order in the input file, you can simply write:
jq -r '[.[]] | @csv' palanikumar.json
使用给定的输入,将产生以下CSV:
With the given input, this produces the following CSV:
"ca",812,404,130756,"hit"
"ua",206996,301,142,"unknown"
"ua",206996,0,0,"unknown"
添加标题和尾部分号(如果您确实需要它们)是一项(非常容易的)练习.
Adding the headers and the trailing semicolons (if you really want them) is left as a (very easy) exercise.
如果键的顺序发生变化或可能发生变化,则可以使用以下内容来生成合适的CSV,假设应该使用输入流中第一个对象中的键的顺序:
If the ordering of the keys varies or might vary, then the following could be used to produce suitable CSV, assuming that the ordering of the keys in the first object in the input stream should be used:
input
| . as $first
| keys_unsorted as $keys
| $keys, [$first[]], (inputs | [.[$keys[]]]) | @csv
jq的适当调用将同时包含-n和-r命令行选项.
The appropriate invocation of jq would include both the -n and -r command-line options.
这篇关于如何使用jq将json转换为csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!