1

I have a JSON file with a bunch of different zip codes. What I want to do is leverage the Google Maps API to retrieve the City associated with a zip code, and then write it to the JSON file.

So far I have a script which is correctly grabbing the city from the results. How would I go about writing these cities to the JSON file?

Here's my JSON data:

[
  {
    "State": "Oklahoma",
    "ZIP": 73169
  },
  {
    "State": "Oklahoma",
    "ZIP": 73169
  },
  {
    "State": "Oklahoma",
    "ZIP": 73170
  },
  {
    "State": "Oklahoma",
    "ZIP": 73172
  },
  {
    "State": "Oklahoma",
    "ZIP": 73173
  }
]

And here's my script:

$(function() {
  $.get('locations.json', function(data) {
    $.each(data, function(i, item) {
      var zip = item.ZIP;
      var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&key=AIzaSyD_YqB4d_-xKcmNP9jJCiPkJYDS8J3f6pI";
      $.get(url, function(loc) {
          for(var i=0;i<loc.results.length;i++) {
            var address = loc.results[i].formatted_address;
            var city = address.split(',', 1)[0]
            console.log(city);
          }
      });
    });
  });
});

Here's a Plunker

UPDATE:

I found a way to write to my JSON file using NodeJS from this question, the code below successfully updates the "City" to "test" for each of my JSON objects, now I guess I just need help on incorporating this into my jQuery code:

fs = require('fs');
var m = JSON.parse(fs.readFileSync('locations.json').toString());
m.forEach(function(p){
    p.City = "test";
});
fs.writeFile('locations.json', JSON.stringify(m));

I would also be willing to use PHP if that would be easier.

Yet another attempt(closest to what I'm trying to do):

The plan is to only use this script once to populate the JSON with all of the cities. So I figured I would try to do it client-side where I can just log out some JSON data and then copy/paste it manually rather than relying on server-side code to do it for me. That brought me to this solution:

$(function() {
   var item = [];
   var locations = [
     {
       "State": "Oklahoma",
       "ZIP": "73169",
       "City": ""
     },
     {
       "State": "Oklahoma",
       "ZIP": "73169",
       "City": ""
     },
     {
       "State": "Oklahoma",
       "ZIP": "73170",
       "City": ""
     },
     {
       "State": "Oklahoma",
       "ZIP": "73172",
       "City": ""
     },
     {
       "State": "Oklahoma",
       "ZIP": "73173",
       "City": ""
     }
   ];

      $.each(locations, function(i, item) {
    var zip = item.ZIP;
    var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&key=AIzaSyA75wif8_yewifGSqVFnR3U50zuW_EnAns";
    $.get(url, function(loc) {
     for(var i=0;i<loc.results.length;i++) {
      var address = loc.results[i].formatted_address;
      var city = address.split(',', 1)[0];
      item.City = city;
      console.log(item);
     }
    });
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If I log out item within the for statement, it returns everything correctly. How could I output this as a single array in JSON format?

Community
  • 1
  • 1
user13286
  • 3,027
  • 9
  • 45
  • 100
  • Care to explain the downvote? – user13286 May 08 '17 at 16:47
  • Are you trying to create and save a file in client side JavaScript (ie. running in the browser)? – vesse May 08 '17 at 17:15
  • It doesn't really matter how or where the file is saved, I will just be running this one time to populate the cities into the JSON file and then never using it again. Even if I could just modify the JSON on the client-side with the ability to copy/paste it into the JSON file that would be sufficient. – user13286 May 08 '17 at 17:28

1 Answers1

2

You cannot write a file from browser directly. You could create a blob or a data URL and provide a link from where the file could be downloaded like in this example.

Or, since you have Node.js, maybe just run a script in the shell. This example requires npm install request request-promise-native, but you could use Node.js https API instead. Also, no error handling in the example.

const fs = require('fs');
const http = require('http');
const request = require('request-promise-native');

const baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?key=<your key>&address=';
const locations = JSON.parse(fs.readFileSync('locations.json', 'utf8'));

Promise.all(locations.map((location) => {
  return request
    .get(baseUrl + location.ZIP)
    .then((result) => {
      location.city = JSON.parse(result).results[0].formatted_address.split(',', 1)[0];
      return location;
    });
})).then((results) => {
  fs.writeFileSync('results.json', JSON.stringify(results));
});

Edit: I just read your comment about even copy-paste being sufficient for you. You can use the approach above also in browser, no need for jQuery:

Promise.all(locations.map((location) => {
  return fetch(baseUrl + location.ZIP)
    .then((result) => {
      location.city = result.results[0].formatted_address.split(',', 1)[0];
      return location;
    });
})).then((results) => {
  console.log(JSON.stringify(results));
});
Community
  • 1
  • 1
vesse
  • 4,871
  • 26
  • 35