如何用jq重新格式化sensors命令的JSON输出?
处理sensors命令JSON输出的格式化需求
原始输出
执行sensors -j ftsteutates-i2c-0-73得到的原始JSON输出如下:
{ "ftsteutates-i2c-0-73":{ "Adapter": "SMBus I801 adapter at efa0", "VCC 3.3V":{ "in0_input": 3.331 }, "3.3V AUX":{ "in1_input": 3.359 }, "V_IN (12V)":{ "in2_input": 12.012 }, "VBAT 3.0V":{ "in3_input": 2.692 }, "CPU":{ "fan1_input": 660.000, "fan1_alarm": 0.000, "fan1_fault": 0.000 }, "Chassis":{ "fan3_input": 1200.000, "fan3_alarm": 0.000, "fan3_fault": 0.000 }, "CPU":{ "temp1_input": 51.000, "temp1_alarm": 0.000, "temp1_fault": 0.000 }, "Ambient":{ "temp2_input": 44.000, "temp2_alarm": 0.000, "temp2_fault": 0.000 }, "Core":{ "temp3_input": 54.000, "temp3_alarm": 0.000, "temp3_fault": 0.000 }, "Memory":{ "temp4_input": 42.000, "temp4_alarm": 0.000, "temp4_fault": 0.000 }, "PCH":{ "temp5_input": 54.000, "temp5_alarm": 0.000, "temp5_fault": 0.000 }, "Graphics":{ "temp6_input": 40.000, "temp6_alarm": 0.000, "temp6_fault": 0.000 } } }
最终期望格式
由于CPU的风扇和温度数据会被重复键名覆盖,需要将主键名与子键中的类型标识(in/fan/temp)拼接,得到如下格式化结果:
{ "VCC 3.3V_in": 3.331, "3.3V AUX_in": 3.359, "V_IN (12V)_in": 12.012, "VBAT 3.0V_in": 2.692, "CPU_fan": 660.000, "Chassis_fan": 1200.000, "Ambient_temp": 44.000, "Core_temp": 54.000, "Memory_temp": 42.000, "PCH_temp": 54.000, "Graphics_temp": 40.000 }
正确的jq命令
使用以下命令可以实现需求:
sensors -j ftsteutates-i2c-0-73 | jq '."ftsteutates-i2c-0-73" | del(."Adapter") | to_entries | map(.value | to_entries | select(.key | endswith("_input")) | map({key: "\($parent.key)_\(.key | capture("(in|fan|temp)").captures[0].string)", value: .value})) | flatten | from_entries'
命令解释
."ftsteutates-i2c-0-73" | del(."Adapter"):定位到目标设备节点,删除无用的Adapter字段to_entries:将对象转换为键值对数组,方便遍历处理map(.value | to_entries | select(.key | endswith("_input"))):遍历每个主键对应的子对象,筛选出以_input结尾的子键map({key: "\($parent.key)_\(.key | capture("(in|fan|temp)").captures[0].string)", value: .value}):拼接主键名与子键中的类型标识(in/fan/temp)作为新键,保留对应数值flatten | from_entries:将嵌套数组扁平化,再转换回对象结构
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

