0

How can I do the following in JavaScript? I want to load JSON data from the url "https://data.cityofnewyork.us/resource/734v-jeq5.json". And then, take the JSON data that consists of an array of only 'sat_critical_reading_avg_score'. Any help is greatly appreciated.

import json
import urllib.request

def get_data():
  response = urllib.request.urlopen("https://data.cityofnewyork.us/resource/734v-jeq5.json")
  content = response.read().decode()
  response1 = json.loads(content)
  result = []
  for i in response1:
    try:
      result.append(
        int(i['sat_critical_reading_avg_score'])
      )
    except:
      pass
  return result


print(get_data())

2 Answers 2

1

You can use fetch() and JSON.parse() methods, both built-in JavaScript.

Here a simple example of getting a JSON string from the server, transforming it in to a JS object and outputting the results to the console:

    let JSobject; 

    fetch('https://data.cityofnewyork.us/resource/734v-jeq5.json')
    .then(function(JSONstring) {
        JSobject = JSON.parse(JSONstring);
    });

    console.log(JSobject.sat_critical_reading_avg_score);

For further knowledge on JavaScript I recommend Eloquent JavaScript book. A pretty good book with a free version available online: http://eloquentjavascript.net/

Sign up to request clarification or add additional context in comments.

1 Comment

You can skip JSON.parse to response.json() a built-in method on fetch response.
0

Your code translate to TS/JS: function getData(): const fetchData =

fetch('https://data.cityofnewyork.us/resource/734v-jeq5.json').then(response => {
         let data = JSON.parse(response);
         let result = [];
         for (i in data) {
           try {
             result.push(parseInt(data[i].sat_critical_reading_avg_score));
           } catch (err) {}
         }
         return result;
       });
       return fetchData;

    console.log(getData());

ES7 style simplified:

const data = fetch('https://data.cityofnewyork.us/resource/734v-jeq5.json').then(response => response.json().map(item => item.sat_critical_reading_avg_score));
console.log(data);

2 Comments

Your first code and second code is giving me ReferenceError: fetch is not defined
@Anonymous You can use fetch() and JSON.parse() methods, both built-in JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.