0

im currently trying to figure out what exactly a json file is at this point. Im stumped because instead of trying to console.log my result json, im trying to store it somewhere so I can go through it and extract the author of each post but im not sure if its an array or one big string so I dont know how to store it and go through each element to store the author into another array that will hold authors. Heres what I got so far:

    console.log("Hello")
var postsArr = [];
let author = [];
let jsonPost = "";
//URI encoding here to add to the end of URL
//console.log()
let encodedSearch = encodeURIComponent(search);
console.log()
encodedSearch.replace("%20","+")
  const getPosts = () => {
    const urlPosts = "https://www.reddit.com/search.json?q=";
    let newURL = urlPosts.concat(encodedSearch.toString().replace(/%20/g,"+"))
    console.log(newURL)
    return fetch(newURL)
    .then(res => res.json())
    .then(posts => {
      jsonPost = posts
    })
  }
  getPosts()
  console.log(jsonPost)

Any help or advice is greatly appreciated!

Aviera00
  • 1
  • 4
  • Your question is not very clear. Could you tell exactly what you're trying to achieve here? – Rifat Bin Reza Mar 15 '21 at 07:43
  • I'm trying to store the json file i get from fetch into a variable so that I can access each "element"? or im not sure the right term for it. So when I fetch from that result URL i get a json file containing posts. Each of those posts should be an object that has an author right? – Aviera00 Mar 15 '21 at 07:56
  • you want to save in the browser cache or database? Or do you want to store in a global variable to access from any scope of the page? – Rifat Bin Reza Mar 15 '21 at 07:57
  • Oh i mean that I just want to put it in a variable, im not sure if thats the most efficient way of doing it though – Aviera00 Mar 15 '21 at 08:00
  • I guess you don't know what is JSON. Check here for that: https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it – Rifat Bin Reza Mar 15 '21 at 08:02
  • You can store JSON in a variable and can loop through it to access it's elements – Rifat Bin Reza Mar 15 '21 at 08:03
  • Can you show an example? So i feel like im really close, So When I display the data I see that each object in the JSON file have an author and a title. These objects are considered posts. Im trying to get the author and title of that JSON object and store it as part of a new object in another array – Aviera00 Mar 15 '21 at 08:18
  • JSON objects are defined by key, value pair. Each element in the object has a key and a value for that key. Let's say you get json object `data` from your API request. you can access the `posts` array like `data.posts` and post authors like, `data.posts[i].author`. Just an example of exploring json objects – Rifat Bin Reza Mar 15 '21 at 08:27

1 Answers1

0

Your main problem is that you call getPosts(), but due to the asynchronous nature of Javascript, it will continue the rest of the code while that's waiting for the result. You then print the result before the function is done.

Don't forget your semicolons. You did the replacing of %20 multiple times but really there's no need for it.

console.log("Hello")
var posts = [];
let authors = [];
let jsonPost = {};

getPosts("this is a test");

// Search posts and print results
function getPosts(searchString) {
  const urlPosts = "https://www.reddit.com/search.json?q=" +  encodeURIComponent(searchString);
  console.log(urlPosts);
  return fetch(urlPosts)
    .then(res => res.json())
    .then(posts => {
      // Get request is done
      jsonPost = posts;
      console.log("This is the raw result json object:");
      console.log(jsonPost);

      // Extract and print posts
      posts = jsonPost.data.children.map((o) => o.data);
      console.log("These are the posts:");
      console.log(posts);

      // Extract and print authors
      authors = jsonPost.data.children.map((o) => o.data.author_fullname);
      console.log("These are the authors:");
      console.log(authors);
  });
}
JerMah
  • 693
  • 5
  • 17
  • Wow, thats amazing! Thanks alot, I have a few more questions if your willing to still help out. What is this line doing "posts = jsonPost.data.children.map((o) => o.data);"? So are there 2 different posts being used here? – Aviera00 Mar 15 '21 at 09:23
  • Reddit's API reference isn't very detailed about what results you get back. But basically I opened the response in the develepment console of chrome (network tab). You can then navigate throught he data structure by clicking and use `.property` and `[index]` in your code to get the parts you want. What map does is, it takes every element of an array and does a function on this element to return a new element. That way you can get the usefull things out of arrays for example, without using a for loop. All of this is one 'get' request. There is no 'post'. 'fetch' is shorthand for a get. – JerMah Mar 15 '21 at 10:07
  • So im asking because im now trying to access the authors profile data which is also in the form of JSON and map is not working like it does in your code above. Heres what I'm trying to do: https://pastebin.com/nCdUje1z – Aviera00 Mar 15 '21 at 10:14
  • so in this code "jsonPost.data.children.map((o) => o.data.author" where is the property and where is the index? – Aviera00 Mar 15 '21 at 10:19
  • children is an array, and for each element in children is searches .data.author and returns that. So it's comparable to a foreach but you never see the index. – JerMah Mar 15 '21 at 10:42
  • Your questions are really specific to the reddit api which is a bit peculiar and really I don't know more about it than you. But what you see there are not usernames, they are "fullname" basically a sort of hash. You can get more information about the user by doing this and then going throught he result. And then a 3rd reaquest using his username to get his details. https://www.reddit.com/api/user_data_by_account_ids.json?ids=t2_73kzzawx – JerMah Mar 15 '21 at 10:43
  • Yeah thanks, I was able to figure it out using what you told me. sorry about the bad question im new to javascript and im a little lost right now but im learning slowly but surely. I'll contact you if I have more questions, thanks! – Aviera00 Mar 15 '21 at 11:08