Internet
Seminar

Spring 2019
course
site

Using JSON data in Javascript

I wrote a short program that demonstrates how to download and manipulate JSON data with Javascript code.

I used XMLHttpRequest as my tool for fetching a demo JSON document from the web. Because I was running my code with Node rather than a browser, I had to install the XMLHttpRequest package, which does not come default with the node install. This was simple using the node package manager command:

$ npm install xmlhttprequest

A step-by-step explanation of how the code works is available in the inline comments. Essentially, it downloads JSON data on all US states and territories from here, then selects five "random" states and prints the state name and capital.

Here's what some output looked like from a test run:

λ https://cs.marlboro.college/cours/spring2019/internet/Documents/spring2019/inet/load_json/ node load_json.js
Data recieved and saved.

State/territory name: Rhode Island
Capital: Providence

State/territory name: Kentucky
Capital: Frankfort

State/territory name: U.S. Virgin Islands
Capital: Charlotte Amalie

State/territory name: Wyoming
Capital: Cheyenne

State/territory name: North Carolina
Capital: Raleigh

Again, check out the attached code for all the details of how it works!

I used the following sources while putting it together:

https://cs.marlboro.college /cours /spring2019 /internet /www /guthrie /js_jan31
last modified Sun April 28 2024 12:23 am

attachments [paper clip]

  last modified size
TXT load_json.js Sun Apr 28 2024 12:23 am 3.4K