简体   繁体   English

将 JSON 树导航到来自 Reddit API 的数据

[英]Navigating JSON tree to data from Reddit API

I will try and keep this short.我会尽量保持简短。 I am a current student and have been attempting to retrieve the top 5 posts from the front page of Reddit and display the title and URL on an HTML page.我是一名在校学生,一直在尝试从 Reddit 的首页检索前 5 篇帖子,并在 HTML 页面上显示标题和 URL。 It is probably something really simple, but I can't get it to work.这可能是非常简单的事情,但我无法让它发挥作用。 I want to pass the data to my Handlebars template from a single variable.我想将数据从单个变量传递到我的 Handlebars 模板。 I keep receiving an unhandled promise warning.我不断收到未处理的承诺警告。 Here is my code.这是我的代码。

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.children.data.title,
    url: data.children.data.url_overriden_by_dest
    }
    ];
});

The data object is structured differently than they way you've coded it. data对象的结构与您对其进行编码的方式不同。 Here is how to extract the information you want from the first child:以下是如何从第一个孩子中提取您想要的信息:

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.data.children[0].data.title,
    url: data.data.children[0].data.url_overriden_by_dest
    }
    ];
});

You might want to check some documentation on how the function fetch works here .您可能想在此处查看有关fetch函数如何工作的一些文档。

Also, check how promises work here .另外,请在此处检查 Promise 的工作方式。

That being said, you have to access the object properties, only when the Promise has finished retrieving the data.话虽如此,您必须访问对象属性,只有当 Promise 完成检索数据时。 One way is using the Promise.allSettled function.一种方法是使用Promise.allSettled函数。

Please see the following snippet working, with a slightly different way of organizing it:请查看以下代码片段,其组织方式略有不同:

 const url = "https://www.reddit.com/.json?limit=5"; const promise = fetch(url).then(res => res.json()); function formatHandlebarsData(data) { const childrenObj = data.value.data.children; return childrenObj.map(element => ({ title: element.data.title, url: element.data.url })); } Promise.allSettled([promise]).then(([data]) => { const handlebarsData = formatHandlebarsData(data); // You can use the object now console.log(handlebarsData); });

Awesome.惊人的。 I was able to get it working with我能够让它工作

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.data.children[0].data.title,
    url: data.data.children[0].data.url_overriden_by_dest
    }
    ];
});

Thanks!谢谢!

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

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