Python Write a JSON temporary file from a dictionary

筅森魡賤 提交于 2020-01-04 04:26:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!