英文:
Parse json response using Javascript
问题
我需要使用Javascript从JSON响应中提取数据。我已经检查了一些帖子,但没有找到适合我的问题的解决方案。JSON数据如下:
{"apple":{"count":4},"orange":{"messageCount":3},"banana":{"messageCount":2},"grapes":{"messageCount":5}}
我尝试使用以下代码来获取每个水果的计数,比如苹果:
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj[0];
但返回的是未定义。
请问如何使用Javascript获得每种水果的计数并存储在一个变量中。谢谢。
英文:
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
答案1
得分: 0
使用`JSON.parse()`方法将其存储在`data`中,并通过访问数据对象的属性获取每种水果的计数
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
英文:
use the JSON.parse()
method and store it in the data
and get count of each fruit by accessing property of the data object
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论