Exploring JSON API data from Node REPL

jiadar

Javin Lacson

Posted on February 16, 2020

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
wget https://www.reddit.com/r/videos.json

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.

node
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')
typeof(videos)

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)
typeof(videos_dict)

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 videos_dict.data.children[n].data.url.

Object.keys(videos_dict)
typeof(videos_dict.data)
Object.keys(videos_dict.data)
typeof(videos_dict.data.children)
Object.keys(videos_dict.data.children)
typeof(videos_dict.data.children)
Object.keys(videos_dict.data.children[0])
typeof(videos_dict.data.children[0].data)
Object.keys(videos_dict.data.children[0].data)
videos_dict.data.children[0].data.url

Now, map over the videos_dict.data.children to print all the video URL's.

videos_dict.data.children.map( (child) => { return child.data.url } )

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

💖 💪 🙅 🚩
jiadar
Javin Lacson

Posted on February 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related