使用Javascript解析JSON响应。

huangapple go评论87阅读模式
英文:

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 = &#39;{&quot;apple&quot;:{&quot;count&quot;:4},&quot;orange&quot;:{&quot;messageCount&quot;:3},&quot;banana&quot;:{&quot;messageCount&quot;:2},&quot;grapes&quot;:{&quot;messageCount&quot;:5}}&#39;;
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 -->

huangapple
  • 本文由 发表于 2023年2月16日 18:39:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定