json - 如何使用 JQ 在命令行中将 JSON 列表提取到 CSV 中?

标签 json export-to-csv precision jq

我有以下 JSON 数据:

% cat test2 

{"day":"2020-07-15","map":
{"a":"ask","b":"bid","t":"timestamp"},"msLatency":52,"pair":"EUR/USD","status":"success","ticks":[
{"b":1.14105,"a":1.14106,"x":48,"t":1594771200000},
{"b":1.14105,"a":1.14106,"x":48,"t":1594771201000},
{"b":1.14103,"a":1.14104,"x":48,"t":1594771202000},
{"b":1.141,"a":1.1413,"x":48,"t":1594771203000},
{"b":1.14103,"a":1.14104,"x":48,"t":1594771205000},
{"b":1.14094,"a":1.14095,"x":48,"t":1594778803000}],"type":"forex"}

我想要得到:

1.14105,1.14106,1594771200000
1.14105,1.14106,1594771201000
1.14103,1.14104,1594771202000
1.141,1.1413,1594771203000
1.14103,1.14104,1594771205000
1.14094,1.14095,1594778803000

理想情况下,输出还应该用零填充,其中 1 和 5 是参数,用于指定前两列是具有 1 个自然位和 5 个小数位的数字(尽管可以使用 awk 轻松完成此步骤):

1.14105,1.14106,1594771200000
1.14105,1.14106,1594771201000
1.14103,1.14104,1594771202000
1.14100,1.14130,1594771203000
1.14103,1.14104,1594771205000
1.14094,1.14095,1594778803000

我已经用 JQ 尝试过:

 % cat test2 | jq '.ticks'
[
  {
    "b": 1.14105,
    "a": 1.14106,
    "x": 48,
    "t": 1594771200000
  },
  {
    "b": 1.14105,
    "a": 1.14106,
    "x": 48,
    "t": 1594771201000
  },
  {
    "b": 1.14103,
    "a": 1.14104,
    "x": 48,
    "t": 1594771202000
  },
  {
    "b": 1.141,
    "a": 1.1413,
    "x": 48,
    "t": 1594771203000
  },
  {
    "b": 1.14103,
    "a": 1.14104,
    "x": 48,
    "t": 1594771205000
  },
  {
    "b": 1.14094,
    "a": 1.14095,
    "x": 48,
    "t": 1594778803000
  }
]

但我不知道如何将其转换为 CSV。

编辑: 作为引用,我之前有过以下解析,这里使用 JQ 是更简单的选择:

cat test2 |
sed -e 's/{\"/#{\"/g' |
tr '#' '\n' |
grep -v "timestamp" |
grep -v "day" |
sed '/^[[:space:]]*$/d' |
sed 's/].*$//g' |
sed 's/{//g' |
sed 's/},//g' |
sed 's/}//g' |
sed 's/\"//g' |
awk -F '[:,]' -v decimal_places=5 -v integer_places=1 '{
        for(i=1; i<=NF; i=i+2) {
                value[$i]=$(i+1);
        };
        format_price="%0" integer_places "." decimal_places "f"
        format=format_price " " format_price " %d\n"
        printf(format,value["b"],value["a"],value["t"]);
}'

最佳答案

解决方案如下:

jq -r '.ticks[] | [.b, .a, .t] | join(",")' test2

1.14105,1.14106,1594771200000
1.14105,1.14106,1594771201000
1.14103,1.14104,1594771202000
1.141,1.1413,1594771203000
1.14103,1.14104,1594771205000
1.14094,1.14095,1594778803000

它不会填充 5 位数字。我不知道如何在 jq 中做到这一点。我仍然认为另一种语言会更容易。

关于json - 如何使用 JQ 在命令行中将 JSON 列表提取到 CSV 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62938833/

相关文章:

java - 无法为 map 设置正确的 JSON 格式

json - 在Google Data Studio中提取json字符串字段

php - Greasemonkey AJAX 请求不发送数据?

postgresql - 在函数中使用 plpgsql 复制到 csv 的动态 csv 文件导出错误

JavaFX 标签 double

mysql - 如何将十进制计算结果存储在mysql中并像在内存中一样将其检索回来

opengl-es - 着色器 MAD 优化和精度问题

javascript - json 中数组和对象的混淆

javascript - TableExport jquery 插件 : Filename and Extension issue

java - 为什么 Jackson 在重建配置模式以构建 CSV 记录行时将包含逗号的字符串括起来?