问题
I'm working on a python(3.6) project in which I need to write a JSON file from a Python dictionary.
Here's my dictionary:
{'deployment_name': 'sec_deployment', 'credentials': {'type': 'type1', 'project_id': 'id_001',}, 'project_name': 'Brain', 'project_id': 'brain-183103', 'cluster_name': 'numpy', 'zone_region': 'europe-west1-d', 'services': 'Single', 'configuration': '', 'routing': ''}
And I need to write credentials
key to a JSON file.
Here's how I have tried:
tempdir = tempfile.mkdtemp()
saved_umask = os.umask(0o077)
path = os.path.join(tempdir)
cred_data = data['credentials']
with open(path + '/cred.json', 'a') as cred:
cred.write(cred_data)
credentials = prepare_credentials(path + '/cred.json')
print(credentials)
os.umask(saved_umask)
shutil.rmtree(tempdir)
It's not writing a JSON formatted file, then generated file is as:
{
'type': 'type1',
'project_id': 'id_001',
}
it comes with single quotes instead of double quotes.
回答1:
Use the json
module
Ex:
import json
with open(path + '/cred.json', 'a') as cred:
json.dump(cred_data, cred)
来源:https://stackoverflow.com/questions/51081782/python-write-a-json-temporary-file-from-a-dictionary