Save Json dictionary to txt

Asked

Viewed 915 times

0

How can I save a. json dictionary of a requests in txt. I tried to do it this way but it didn’t 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 "data.txt" file but does not write the json dictionary data.

  • Wouldn’t it just be saving the content of the answer in the file? If the return is already in JSON format, just save it in the desired file, have no reason to convert to object and then save it.

1 answer

1

change the line:

arquivo.write(response)

for

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

are two things that were missing there: the method .json() of Response (which is created by requests) is measured and transferred in a Python object - composed of nested dictionaries or lists, strings, numbers and "None"s - which are the objects that JSON can de-serialize alone.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.