使用jq根据name字段为JSON生成对应偏移时长的endate字段
问题描述
原始JSON数据:
{ "data": [ { "id": 1, "startdate": "2022-10-14 12:05:49", "name": "hello1", "run_status_index": 29 }, { "id": 2, "startdate": "2022-10-14 11:45:36", "name": "hello2", "run_status_index": 95 } ] }
需求:
- 当
name字段值为hello1时,给startdate增加18小时,新增endate字段 - 当
name字段值为hello2时,给startdate增加24小时,新增endate字段
期望输出:
{ "data": [ { "id": 1, "startdate": "2022-10-14 12:05:49", "endate": "2022-10-15 06:05:49", "name": "hello1", "run_status_index": 29 }, { "id": 2, "startdate": "2022-10-14 11:45:36", "endate": "2022-10-15 11:45:36", "name": "hello2", "run_status_index": 95 } ] }
用户尝试的无效jq代码:
jq 'def n: if .data == "" then null else . end; .endate = ((.startdate|n) // "")'
解决方案
正确的jq命令如下:
jq '.data[] |= ( .endate = ( .startdate | fromdateiso8601 + (if .name == "hello1" then 18*3600 else 24*3600 end) | strftime("%Y-%m-%d %H:%M:%S") ) )' input.json
代码说明:
.data[] |=:遍历data数组中的每个对象,直接修改原对象(无需重新构造数组)fromdateiso8601:将startdate的字符串格式转换为Unix时间戳(以秒为单位),便于时间计算- 时间累加逻辑:根据
name的值选择添加18小时(183600秒)或24小时(243600秒)的秒数 strftime("%Y-%m-%d %H:%M:%S"):将计算后的时间戳转换回与startdate一致的字符串格式- 最终将计算结果赋值给新增的
endate字段
注意:
- 需确保使用jq 1.6及以上版本,该版本支持
fromdateiso8601和strftime函数 - 如果
startdate格式非标准ISO8601,需调整时间转换逻辑
内容的提问来源于stack exchange,提问作者j smith
相关产品推荐
相关产品推荐

