gpt4 book ai didi

javascript - 返回随机 JSON 对象

转载 作者:行者123 更新时间:2023-11-28 11:04:45 24 4
gpt4 key购买 nike

我在 AWS 服务器上有 JSON,我可以使用 JQuery 访问它,并且在该 json 文件中有几百个对象,我希望循环遍历并随机挑选一个对象。然后获取该对象的属性。

这是 JSON:

 {  
"1":{
"title":"Sailing for Kids",
"ISBN":"1909911267"
},
"2":{
"title":"True Spirit: The Aussie girl who took on the world",
"ISBN":"413513243"
},
..........

这就是我尝试获取 json 对象的方式。

$(document).ready(function(){
$.ajax({
crossOrigin: true,
url : "https://link/to/file.json",
type : "GET",
success:function(data){
var randomItem = data[Math.random() * data.length | 0];

// take only the element with index 0
alert(randomItem[0]);
}
});
});

但是,警报仅显示一个字符。像这样:

enter image description here

如何循环遍历所有返回的 JSON 文件,选择一个对象,然后获取属性(标题/ISBN)以便我可以使用它们?

最佳答案

[
{
"1":{
"title":"Sailing for Kids",
"ISBN":"1909911267"}
},
{
"2":{
"title":"True Spirit: The Aussie girl who took on the world",
"ISBN":"413513243"}
}
]

您可能需要按照上面的方式构建 JSON

关于javascript - 返回随机 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com