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()
2

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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'.
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.
You are right. It makes sense only if you want to pretty print

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.