1

I have a JSON file that has many instances like this..:

{
  "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
},

And so forth. I need to assign a variable, say var1 to the sensor value in:

{
  "SensorApp": "Open Hardware Monitor",
  "SensorClass": "Temperature",
  "SensorName": "Intel Core i7-4790: CPU Package",
  "SensorValue": "32",
  "SensorUnit": "C",
  "SensorUpdateTime": 0
},

I've tried a few questions already in stackoverflow, however none of them seem to work with multi-lined JSON files.

Any ideas how i can achieve this?

1 Answer 1

6

I'm not sure if you want to change the value in the json file to a value of a shell variable or if you want to set a shell variable to the value of the SensorValue field in the json.

However, for both tasks you can use jq:

  • Iterating over json values in bash
jq -r '.[].SensorValue' file.json | while read -r value ; do
    # Do something useful with the value
    echo "$value"
done
  • Modifying a json file from bash
VALUE=123
jq ".[].SensorValue = $VALUE" file.json

Update: In comments you told you want to extract the SensorValue out of that json object where SensorName equals "Intel Core i7-4790: CPU Package". In jq you are using the select() function for that:

jq -r '.[] | select(.SensorName == "Intel Core i7-4790: CPU Package").SensorValue' file.json

Output:

32
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Sorry, i wrote this question very late at night. I need to pull the values out of the json file. With your jq solution, how would i set it to only pull the value from a specific section? Right now it just spits back all the matching variables. For example, i only want the value immediately following " "Intel Core i7-4790: CPU Package",".
@user2809413 What you have in mind is possible with jq and is one of it's key features. I have updated my answer and added an example. Note that jq is getting more and more a standard tool for working with json in the shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.