从Python中的JSON响应数据创建JSON文件

从Python中的JSON响应数据创建JSON文件,python,json,file,python-requests,python-3.6,Python,Json,File,Python Requests,Python 3.6,我想从REST请求中获取json响应数据,并创建一个实际的json文件。我试过这样的方法,但没用。本质上,它只是打印标题。有什么建议吗 params = {'f': 'json', 'where': '1=1', 'geometryType': 'esriGeometryPolygon', 'spatialRel': 'esriSpatialRelIntersects','outFields': '*', 'returnGeometry': 'true'} r = requests.get('h

我想从REST请求中获取json响应数据,并创建一个实际的json文件。我试过这样的方法,但没用。本质上,它只是打印标题。有什么建议吗

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()
使用json模块

如果需要,可以使用indent参数以非常漂亮的方式打印

json.dump(my_data, f, indent=2)

看看json.dumpcslfJson可能是OK的重复,我刚刚尝试了cslfJson=json.loadsr.json,它创建了一个字典,然后我与openpath一起使用,“w”作为f:json.dumpcslfJson,f,indent=2。我得到了以下错误-TypeError:JSON对象必须是str、bytes或bytearray,而不是“dict”。这有点毫无意义。没有理由加载JSON只是为了将其转储回文件。直接保存回复内容就行了。你说得对。只有当你想要漂亮的印刷品时,它才有意义
json.dump(my_data, f, indent=2)