0

I want to take the json response data from a REST request and create an actual json file. I tried something like this, but it did not work. Essentially, it just prints the headers. Any suggestions?

params = {'f': 'json', 'where': '1=1', 'geometryType': 'esriGeometryPolygon', 'spatialRel': 'esriSpatialRelIntersects','outFields': '*', 'returnGeometry': 'true'}
r = requests.get('https://hazards.fema.gov/gis/nfhl/rest/services/CSLF/Prelim_CSLF/MapServer/3/query', params)

cslfJson = r.json()
path = r"C:/Workspace/Sandbox/ScratchTests/cslf.json"
file = open(path, 'w')
for line in cslfJson:
    file.write(line + "\r\n")

file.close()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
gwydion93
  • 1,681
  • 3
  • 28
  • 59

1 Answers1

1

use the json module

my_data = json.loads(r.json())
# my_data is a dict mapping the JSON

with open(path, 'w') as f:
    json.dump(my_data, f)

if you want, you can print in pretty way using the indent parameter

json.dump(my_data, f, indent=2)
Massimo Costa
  • 1,864
  • 15
  • 23
  • OK, I just tried `cslfJson = json.loads(r.json())` which creates a dictionary, then I used `with open(path, 'w') as f: json.dump(cslfJson, f, indent=2)`. I got the following error - `TypeError: the JSON object must be str, bytes or bytearray, not 'dict'`. – gwydion93 Aug 20 '18 at 19:55
  • This is a bit pointless. There's no reason to load the JSON only to dump it back to a file. Just save the response content directly. – Daniel Roseman Aug 20 '18 at 21:09
  • You are right. It makes sense only if you want to pretty print – Massimo Costa Aug 20 '18 at 21:13