Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
Abdul Rehman Avatar asked Jun 28 '18 11:06

Abdul Rehman


People also ask

Can we convert dictionary to JSON in Python?

Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.

What is JSON dump Python?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

Does JSON use dictionary?

JSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists. Here is a simple example with just 4 attribute/value pairs.


1 Answers

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

like image 133
HaoZeke Avatar answered Sep 17 '22 18:09

HaoZeke