我有一个JSON文件,它有很多这样的实例..:
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Core #4",
"SensorValue": "31",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Package",
"SensorValue": "32",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Clock",
"SensorName": "Intel Core i7-4790: CPU Core #1",
"SensorValue": "3899.165",
"SensorUnit": "MHz",
"SensorUpdateTime": 0
},
等等。我需要为传感器值分配一个变量,比如var1:
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Package",
"SensorValue": "32",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
我已经在stackoverflow中尝试了一些问题,但是它们似乎都不适用于多行JSON文件。
我是如何实现这一目标的?
答案 0 :(得分:6)
我不确定您是否要将json文件中的值更改为shell变量的值,或者您是否要将shell变量设置为SensorValue
字段的值JSON。
但是,对于这两项任务,您可以使用jq
:
jq -r '.[].SensorValue' file.json | while read -r value ; do
# Do something useful with the value
echo "$value"
done
VALUE=123
jq ".[].SensorValue = $VALUE" file.json
更新:在评论中,您告诉您要从SensorValue
等于SensorName
的json对象中提取"Intel Core i7-4790: CPU Package"
。在jq
中您正在使用select()
函数:
jq -r '.[] | select(.SensorName == "Intel Core i7-4790: CPU Package").SensorValue' file.json
输出:
32