2

Let's say that we have this kind of JSON file:

{
  ... 
  "quotes":{
     "SOMETHING":10,
     ...
     "SOMETHING_ELSE":120.4,
     ...
  }   }

How can I obtain those values and use them in order to add them together?

Am I able to do even this?

#!/bin/bash

#code ...

echo "$SOMETHING + $SOMETHING_ELSE" | bc

#code ...

#exit

I will obtain the JSON file with wget command. All I want is the content from this file.

Can you help me, please? I am a beginner in shell programming.

Thodoris
  • 49
  • 1
  • 2
  • 4

3 Answers3

5

I usually use jq, a really fast json parser, to do this kind of things (because parsing a json file with tools like awk or sed is really error-prone).

Given an input file like this:

# file: input.json
{
  "quotes":{
    "SOMETHING":10,
    "SOMETHING_ELSE":120.4
  }
}

You can obtain the sum of the 2 fields with a simple filter:

jq '.quotes.SOMETHING + .quotes.SOMETHING_ELSE' input.json
# output -> 130.4

NOTE: jq is available in every major linux distribution. In a debian-derivative system you can install with a sudo apt-get install jq.

Giuseppe Ricupero
  • 6,134
  • 3
  • 23
  • 32
1

This will print out the sum of the selected lines' floats.

#!/bin/bash
awk '{ if ($1 ~ /"SOMETHING":/) {print}; if ($1 ~ /"SOMETHING_ELSE":/) {print} }' $1 | cut -d: -f2 | cut -d, -f1 | awk '{s+=$1};END{print s}'

This finds the lines you want, the plucks out the numbers, and adds them.

Erik Bryer
  • 96
  • 6
0

You should look up and learn jq as shown in Read the json data in shell script.

The tools in a "normal" shell installation like awk and sed all predate JSON by decades, and are a very very bad fit. jq is worth the time to learn.

Or use Python instead.

Community
  • 1
  • 1
Ewan Mellor
  • 6,747
  • 1
  • 24
  • 39