read.json file :
{
\"Username\" : \"admin\",
\"Password\" : \"admin\",
\"Iterations\" : 5,
\"Decimal\" : 5.5,
\"tags\" : [\"hello\", \"b
The issue is that you're converting your dictionary to string using python representation which prefers simple quotes.
As Vikash answer states, no need to convert to string (you're losing the structure). Change your data, then let json.dump
handle the dict to text procedure, this time respecting json format, and using double quotes.
Your question was mentionning "prettying" the output, you can achieve this by adding extra params to json.dump
data["Username"] = "newuser" # change data
with open("write.json", "w") as f:
json.dump(data,f,indent=4,sort_keys=True)
now file contents is:
{
"Decimal": 5.5,
"Iterations": 5,
"Password": "admin",
"Username": "newuser",
"Value": 5,
"tags": [
"hello",
"bye"
]
}
indent
: choose indentation level. Has the nice effect of "prettying" the outputsort_keys
: if set, the keys are sorted alphabetically, which guarantees the same output every time (python key order is random)you can directly dump json data to file. Docs
import json
with open('read.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=True, indent=4)
# sort_keys, indent are optional and used for pretty-write
To read json from file:
with open('read.json') as data_file:
data = json.load(data_file)