Save Json dictionary in txt

0

How can I save one. dictionary json from a requests in txt. I tried to do this way more did not work.

import requests
import json

url = requests. get("https://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=46201")
response = json.loads(url.text)

arquivo = open("dados.txt", "w")
arquivo.write(response)
arquivo.close()

It creates the file "data.txt" plus it does not write the json dictionary data.

    
asked by anonymous 08.11.2018 / 03:57

1 answer

1

Change the line:

arquivo.write(response)

by

json.dump(response.json(), arquivo)

There are two things that were missing there: the .json() of response (which is created by requests) is drawn and transofmrado in a Python object - composed of nested dictionaries or lists, strings, numbers and None - which are the objects that JSON can de-serialize on its own.

And in the sequence we have already passed that same object to the function dump of the json module - which serializes this simple object back to a string, and writes this string to a file.

Take a look at the json.dump documentation - there are optional parameters that allow that the final formatting in the file is more practical to be viewed / edited manually - or more compact, if the idea is that the file is always read and written by other programs.

    
08.11.2018 / 14:21