Heinz
Heinz

Reputation: 85

Extracting data from a string in Bash

I have data pulled via curl which looks like this: foo=[{"date":"2020-06-14","visitors":"323","pageviews":"392"},{"date":"2020-06-15","visitors":"152","pageviews":"172"}

What I want to do is add all of the visitor numbers and assign them to a variable, and add all of the pageviews and assign them to a variable.

I want to disregard the rest of the data.

I have no idea where to start with this.

Upvotes: 1

Views: 77

Answers (1)

Léa Gris
Léa Gris

Reputation: 19675

Computing your pageview sum with parsing the JSON reply with jq:

json_answer='[{"date":"2020-06-14","visitors":"323","pageviews":"392"},{"date":"2020-06-15","visitors":"152","pageviews":"172"}]'

page_views="$(jq -r '[.[].pageviews|tonumber]|add' <<<"$json_answer")"

echo "$page_views"

Output:

564

Upvotes: 1

Related Questions