1

I need to extract data from json response using Javascript. I have checked posts but couldnt find a fitting solution for my problem. The json:

{"apple":{"count":4},"orange":{"messageCount":3},"banana":{"messageCount":2},"grapes":{"messageCount":5}}

I have tried to get the count of each item, eg apple using the below code:

const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj[0];

But returns undefined.

How can i acheive the count of each fruit and store in a variable using Javascript. Thanks

  • 3
    `obj` is an Object, so accessing it by index will not retrieve anything. What output are you expecting to see? – Rory McCrossan Feb 16 '23 at 10:40
  • 1
    Maybe this helps: [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Felix Kling Feb 16 '23 at 10:42

1 Answers1

0

use the JSON.parse() method and store it in the data and get count of each fruit by accessing property of the data object

const response = '{"apple":{"count":4},"orange":{"messageCount":3},"banana":{"messageCount":2},"grapes":{"messageCount":5}}';
const data = JSON.parse(response);

const appleCount = data.apple.count;
const orangeCount = data.orange.messageCount;
const bananaCount = data.banana.messageCount;
const grapesCount = data.grapes.messageCount;

console.log(appleCount);  
console.log(orangeCount);  
console.log(bananaCount); 
console.log(grapesCount);  
Rory
  • 437
  • 1
  • 13