如何在Unix环境下使用jq工具将多层级JSON解析为CSV?
多层级JSON转CSV:每条交易复用公共信息
需求背景
给定如下多层级JSON结构:
{ "id": "id123", "details": { "prod": "prod123", "etype": "type1" }, "accounts": [ { "bankName": "bank123", "accountType": "account123", "openingBalance": "bal123", "fromDate": "2023-01-01", "toDate": "2023-01-01", "missingMonths": [], "transactions": [ { "dateTime": "2020-12-01", "description": "a very long string", "amount": -599.0, "bal": 8154.83, "type": "Debit" }, { "dateTime": "2020-12-01", "description": "a very long string; a very long string", "amount": -4000.0, "balanceAfterTransaction": 4154.83, "type": "Debit" } ] } ], "accountid": "sample123" }
需要将其转换为CSV格式,要求每笔交易记录重复所有公共层级的信息,目标格式如下:
id,prod,etype,bankName,accountType,openingBalance,fromDate,toDate,dateTime,description,amount,bal,type,accountid id123,prod123,type1,bank123,account123,bal123,2023-01-01,2023-01-01,2020-12-01,"a very long string",-599.0,8154.83,Debit,sample123 id123,prod123,type1,bank123,account123,bal123,2023-01-01,2023-01-01,2020-12-01,"a very long string; a very long string",-4000.0,4154.83,Debit,sample123
现有部分jq命令:jq --raw-output '[ .id, .details[], .accounts[].transactions[] ]',需要补充完整实现。
完整解决方案
使用以下完整的jq命令即可实现需求:
jq --raw-output ' # 定义CSV表头 ["id", "prod", "etype", "bankName", "accountType", "openingBalance", "fromDate", "toDate", "dateTime", "description", "amount", "bal", "type", "accountid"] | @csv, # 遍历每个账户,再遍历该账户下的每笔交易 (.accounts[] | . as $account | .transactions[] | [ $id, $details.prod, $details.etype, $account.bankName, $account.accountType, $account.openingBalance, $account.fromDate, $account.toDate, .dateTime, .description, .amount, # 兼容交易字段中的"bal"或"balanceAfterTransaction" (.bal // .balanceAfterTransaction), .type, $accountid ]) | @csv ' input.json
关键细节说明
- 表头生成:先定义包含所有目标列的数组,通过
@csv过滤器转换为标准CSV表头行。 - 层级遍历:
- 先遍历顶层的
accounts数组,将当前账户对象存入变量$account,方便后续复用其字段。 - 再遍历当前账户下的
transactions数组,对每笔交易生成一条CSV记录。
- 先遍历顶层的
- 字段复用:每笔交易记录中,复用顶层的
id、details下的字段,以及当前账户的bankName、accountType等公共信息。 - 字段兼容:交易中的余额字段存在两种命名(
bal和balanceAfterTransaction),使用//运算符优先取.bal,不存在则取.balanceAfterTransaction。 - 格式合规:通过
@csv过滤器自动处理带特殊字符(如分号、空格)的字符串,将其包裹在双引号中,符合CSV格式规范。
使用方式
- 将原始JSON保存为
input.json文件,执行上述命令即可输出目标CSV。 - 也可以通过管道直接传递输入,例如:
cat input.json | jq --raw-output '...'
内容的提问来源于stack exchange,提问作者Abhishek Jain
相关产品推荐
相关产品推荐

