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.
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.
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.
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.
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:
tempfile
, and ensure that there's a name with NamedTemporaryFile
json
fileflush()
Note that we can keep the file for longer with delete=False
when calling the NamedTemporaryFile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With