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.

1
  • @JoshJolly No, this is not one I wanted. Commented Dec 13, 2015 at 20:07

3 Answers 3

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.

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

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.