-2

I have a JSON file that is being generated from an API and stored into a variable myJson that looks like this:

    {
    "results": [
        {
          "term": "A",
          "count": 1569
        },
        {
          "term": "B",
          "count": 1375
        },
        {
          "term": "C",
          "count": 1372
        }
    ]
    }

Is there any approach to add up all of the numerical values in the "count" entry and store it as a string into a variable?

So: stringVariable = 1569 + 1375 + 1372

Note: This is just a small snippet of a giant JSON file so I believe will need a formula of some sort.

Thanks!!

cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 1
    What have you tried so far? The community won't help you if you expect us to solve everything – Mμ. Jul 24 '17 at 02:38
  • JSON is a data format, not a programming language. It does not have methods. – Dan Lowe Jul 24 '17 at 02:42
  • @DanLowe I assume s/he means method in the sense of "approach" – Timothy Jul 24 '17 at 02:42
  • Is it just a straight forward solution in which you just need to traverse through the list, pickup the results(index).count and sum it up ? – Nexus Jul 24 '17 at 02:43
  • Possible duplicate of [JavaScript loop through json array?](https://stackoverflow.com/questions/18238173/javascript-loop-through-json-array) – Timothy Jul 24 '17 at 02:44
  • Maybe you could use a "loop". –  Jul 24 '17 at 02:45

1 Answers1

1

Without knowing what language you're asking about, let's use JavaScript.

function add(data) {
    let sum = 0;
    data['results'].slice(1).forEach( obj =>
        sum += obj['count']
    );
    return sum;
}
jhpratt
  • 6,841
  • 16
  • 40
  • 50
  • the only issue i have is that this function is returning `1569 + 1375 + 1372` instead of the sum – cup_of Jul 24 '17 at 03:17
  • that is why when you declare your stringVariable , makes it as int type int stringVariable ... – Nexus Jul 24 '17 at 03:55
  • Sorry, the question made it look like you wanted the string. I'll edit my answer to provide the actual sum. – jhpratt Jul 24 '17 at 04:12