Javascript 如何从json数据中检索数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38900092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:00:57  来源:igfitidea点击:

How to retrieve data from json data

javascriptjson

提问by ROB ENGG

[{"id":7,"message":"This is another test message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}]

That's my response. I try to get a datum. I have tried data.idbut it fails and returns undefined.

这就是我的回应。我试图获得一个数据。我试过了,data.id但它失败并返回undefined

回答by Zombiefledderer

As I assume that you are working with a JSON string, you first have to parse the string into and JSON object. Else you couldn't reach any of the properties.

由于我假设您正在使用 JSON 字符串,因此您首先必须将字符串解析为 JSON 对象。否则,您无法访问任何属性。

parsedData = JSON.parse(data);

Then you can get your property:

然后你可以得到你的财产:

parsedData[0].id

回答by Jonathan Newton

This seems to work just fine

这似乎工作得很好

var data = [{
  "id":7,
  "message":"This is another test message",
  "taker_id":"131",
  "giver_id":"102",
  "status":"0",
  "stamp":"2016-08-11"
}];
console.log(data[0].id);

https://jsbin.com/jewatakize/

https://jsbin.com/jewatakize/

回答by Kerrin631

if you just want to get the id from this one object then data[0].id will work just fine. If you expect to have multiple objects in that same array then you can use a loop. for example if this is angular you can do:

如果您只想从这个对象中获取 id,那么 data[0].id 就可以正常工作。如果您希望在同一个数组中有多个对象,那么您可以使用循环。例如,如果这是有角度的,你可以这样做:

<div ng-repeat='info in data'>
    <p>{{info.id}}</p>
</div>

This will allow you to iterate through multiple objects within the array and get all id's.

这将允许您遍历数组中的多个对象并获取所有 id。