简体   繁体   English

Javascript 打印 JSON Object

[英]Javascript print JSON Object

I want to parse this JSON array and print the salary so this what I have tried so far there is nothing logged in the Console我想解析这个 JSON 数组并打印salary ,所以这是我迄今为止尝试过的,控制台中没有任何记录

if (data.action == 'SendArray') {
  let invites = data.invites
  const obj = JSON.parse(invites)
  const myJSON = JSON.stringify(obj);
  console.log(myJSON.salary)
}

JSON: JSON:

{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}

myJSON is an array of objects. myJSON是一个对象数组。 To log in console need to get each object.要登录控制台需要获取每个 object。 we can use forEach to get each object and then can console log the salary key.我们可以使用forEach来获取每个 object 然后可以控制台记录salary密钥。

 let myJSON =[ {"factioname":"sp-force","inviter":"MohammedZr","salary":5000}, {"factioname":"air-force", "inviter":"Admin","salary":8000}]; myJSON.forEach(obj=> { console.log(obj.salary); });

This const myJSON = JSON.stringify(obj) turns your object back into a string, which you don't want.const myJSON = JSON.stringify(obj)将您的 object 变回您不想要的字符串。

I've done some setup to get your data matching your code but the two things you should note are:我已经完成了一些设置以使您的数据与您的代码匹配,但您应该注意的两件事是:

  1. Iterating through the array of invites using for.. of (you could use forEach instead) and使用for.. of遍历邀请数组(您可以使用forEach代替)和
  2. Using deconstruction to pull out the salary解构拉出工资

 data = { action: 'SendArray', invites: '[{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},{"factioname":"air-force", "inviter":"Admin","salary":8000}]' } if (data.action == 'SendArray') { let invites = data.invites const obj = JSON.parse(invites) for ({salary} of JSON.parse(invites)) console.log(salary)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM