9

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.

Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150
  • Possible duplicate of [Convert string to JSON using Python](https://stackoverflow.com/questions/4528099/convert-string-to-json-using-python) – Natesh bhat Jun 28 '18 at 11:32
  • 1
    It’s not a duplicate, please! – Abdul Rehman Jun 28 '18 at 11:33
  • 2
    Don't write the `dict` directly, write it with the `json` module so it gets properly encoded, i.e. `json.dump(cred_data, cred)` – zwer Jun 28 '18 at 11:38

2 Answers2

19

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

HaoZeke
  • 674
  • 9
  • 19
2

Use the json module

Ex:

import json
with open(path + '/cred.json', 'a') as cred:
    json.dump(cred_data, cred)
Rakesh
  • 81,458
  • 17
  • 76
  • 113