DEV Community

Javin Lacson
Javin Lacson

Posted on

Exploring JSON API data from Node REPL

When just starting out at web programming, it is good to understand the underlying data transport format - JSON and how to interact with it. For this we will use some json data from reddit.

Start up a new directory with a node project and install the JSON library. Then download the json data from reddit.

mkdir json_demo
cd json_demo
npm init
npm install JSON --save

Let's start an interactive session with node so that we can load the data and manipulate it. To do this, run node. In the node REPL (read-eval-print loop), let's first import the fs and JSON modules which we need to read the file from the disk, and parse the data into an object.

var fs = require('fs')
var JSON = require('JSON')

Next, let's read the data from the disk into a variable. We will see that videos is just a string, so we can't really use it that easily.

videos = fs.readFileSync('videos.json', 'utf8')

Let's load the videos into an object with the JSON library. Now we see that videos_dict is a javascript object.

videos_dict = JSON.parse(videos)

We can query the keys to travel into the object and find the data we want. Ultimately I'd like to print the URL's for all the videos. Let's go through the object, determining the type and keys, and descending through the keys until we get to the data we want. Ultimately we find the data at[n].data.url.


Now, map over the to print all the video URL's. (child) => { return } )

For any arbitrary JSON from an unfamiliar API, you can easily explore the data and how to use it in your app!

Top comments (0)