1

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.

5
  • you can start by looking at awk Commented Jul 3, 2020 at 8:39
  • 3
    @CharybdeBE jq would be more suited as it is speciffically designed to handle json Commented Jul 3, 2020 at 8:47
  • @Aserre OP was only mentioning string in the title, but in a result from curl which we cna be sure is json, that true Commented Jul 3, 2020 at 8:48
  • @Heinz As it is your question lacks details. Usually, we expect askers to show their input, an example of their expected output, and what they already tried. Please edit your question to add those missing elements. Commented Jul 3, 2020 at 8:51
  • @Heinz Instead of curl you could have a look at xidel. It can retrieve and parse the JSON data you're after. Commented Jul 3, 2020 at 21:33

1 Answer 1

1

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

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

Comments

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.