通过ID从json文件中获取特定值 [英] get specific value from json file by Id
问题描述
我正在使用$ .get获取可以正常工作的JSON文件内容,当前我想过滤并获取ID为4(最后一个)的项目,我该怎么做? 在Jquery文档中,我没有找到任何提示... http://api.jquery.com/jquery.get/
Im using the $.get to get JSON file content which is working fine,currently I want to filter and get the item with Id 4 (the last one) ,how should I do that ? in the Jquery doc I didn't find some hint to it... http://api.jquery.com/jquery.get/
这是代码:
$.get('tweets.json');
这是JSON文件内容
[
{
"id": 1,
"tweet": "OMG, worst day ever, my BF @BobbyBoo dumped me",
"usersMentioned": [
{
"id": 10,
"username": "BobbyBoo"
}
]
},
{
"id": 2,
"tweet": "OMG, best day ever, my BF came back to me"
},
{
"id": 3,
"tweet": "OMG, worst day ever, just don't ask"
},
{
"id": 4,
"tweet": "@BobbyBoo OMG...just OMG!",
"usersMentioned": [
{
"id": 10,
"username": "BobbyBoo"
}
]
}
]
更新
当我尝试以下内容时,我在then(function(tweets)中没有得到任何东西,tweets是空的 值entry4填充了正确的值...
Currenlty when I try the following I dont get anthing in the then(function (tweets) ,tweets is emtpy the value entry4 is filled with the correct value...
$.get('profile.json').then(function (profile) {
$('#profile-pre').html(JSON.stringify(profile));
$.get('tweets.json', null, null, 'json')
.then(function (response) {
var entry4 = response.filter(function (tweet) {
return tweet.id === 4;
})[0];
return entry4 ;
})
}).then(function (tweets) {
$('#tweets-pre').html(JSON.stringify(tweets));
var myFriend = $.get('friend.json');
return myFriend
}).then(function (friend) {
推荐答案
那是
$.get('tweets.json',null,null,'json')
.then(function(response){
var iAmNumberFour = response.filter(function(tweet){
return tweet.id === 4;
})[0];
});
添加了类型,因为如果您不传递正确的标题,jQuery将不会为您解析JSON.
Added the type since if you don't pass the right headers, jQuery won't parse the JSON for you.
$.get('profile.json').then(function(profile) {
$('#profile-pre').html(JSON.stringify(profile));
return $.get('tweets.json', null, null, 'json')
.then(function(response) {
var entry4 = response.filter(function(tweet) {
return tweet.id === 4;
})[0];
return entry4;
})
}).then(function(entry4) {
$('#tweets-pre').html(JSON.stringify(tweets));
var myFriend = $.get('friend.json');
return myFriend
})
这篇关于通过ID从json文件中获取特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!