Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

pdiaz
pdiaz
16,073 Points

How to convert websites into JSON format for building a blog reader app?

Can you do this for any websites?

1 Answer

Sante Kotturi
Sante Kotturi
7,434 Points

While I'm not 100% sure I understand your question, I believe the short answer is YES and these two javascript methods can get it done: toJSON() and JSON.stringify()

toJSON(): http://www.w3schools.com/jsref/jsref_tojson.asp

JSON.stringify(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

toJSON() returns a JSON object whereas JSON.stringify() returns just a JSON string (no Object structure): http://stackoverflow.com/questions/20734894/difference-between-tojson-and-json-stringify

Hope that helps!

pdiaz
pdiaz
16,073 Points

Okay in the build a blog reader app lesson, you are to receive the json data from the blog with an api. How do I make an api from a blog I wish to extract data from?

Sante Kotturi
Sante Kotturi
7,434 Points

What site are you trying to access this from? I posted an answer to a similar question here

Basically you have to reverse engineer the site to give you the data you want.

There might be an easier way but this is how I would do it. I'm not sure I recommend it and I would only venture down this path if you have some solid web/javascript experience.

Do you see the gray nav bar at the side of the treehouse page? It contains Home, Tracks, Library etc... This will give you back the list of these items in JSON format. You would basically do this for any site, tweaking as needed to get info you need. Here's the basic structure:

// Note this does actually work on the treehouse page
var pages = document.getElementById("main-pages");   // get all the desired elements by the parent class name 
var myList = new Array();     // make a new array to store all our data in, we'll turn this into JSON at the end 
for(var i=0; i< pages.children.length; i++) {      // iterate over each child element
   var holderVar = pages.children[i];          // get the first child element
   var myPage = {}
   myPage.title = holderVar.getAttribute("id"); 
   myList.push(myPage);
} 
var myJSONlist = JSON.stringify(myList);

Maybe there's an easier way, this route isn't trivial.