简体   繁体   中英

Python Write a JSON temporary file from a dictionary

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.

Actually this should be with the more Python 3 native method.

import json,tempfile
config = {"A":[1,2], "B":"Super"}
tfile = tempfile.NamedTemporaryFile(mode="w+")
json.dump(config, tfile)
tfile.flush()
print(tfile.name)

To break this down:

  • We load tempfile , and ensure that there's a name with NamedTemporaryFile
  • We dump the dictionary as a json file
  • We ensure it has been written to via flush()
  • Finally we can grab the name to check it out

Note that we can keep the file for longer with delete=False when calling the NamedTemporaryFile

Use the json module

Ex:

import json
with open(path + '/cred.json', 'a') as cred:
    json.dump(cred_data, cred)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM