9

read.json file :

{
    "Username" : "admin",
    "Password" : "admin",
    "Iterations" : 5,
    "Decimal" : 5.5,
    "tags" : ["hello", "bye"],
    "Value" : 5
}

program.py File:

import json 
with open('read.json') as data_file:
    data = json.load(data_file)

data = str(data)
data.replace("'",'""',10)
f = open("write.json", "w")
f.write(data)

write.json file :

{'Username': 'admin', 'Password': 'admin', 'Iterations': 5, 'Decimal': 5.5, 'tags': ["hello", "bye"], 'Value': 5}

What I want to achieve :

  1. Read JSON data from read.json File
  2. Parse and modify some values from the JSON in my program
  3. Write to another write.json file (In JSON Format)

There are no errors in my code, but the write.json does not contain the values in double quotes(""), it rather as the values wrapped in single quotes making it not a proper JSON format.

What change needs to be done to make the write.json file to contain proper JSON format and also 'pretty-write' to write.json file.

3
  • 1
    You should modify the data (which will be a dict) as you receive it from the json.load() call and write it back to a file using json.dump(). No need to use str() inbetween. Commented Aug 21, 2017 at 7:57
  • you json looks fine ( I check it from my side ) , just change json.load(data) to json.loads(data) Commented Aug 21, 2017 at 7:59
  • @quamrana you are correct loads() takes str not file .json Commented Aug 21, 2017 at 8:07

2 Answers 2

20

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)
Sign up to request clarification or add additional context in comments.

Comments

5

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 output
  • sort_keys: if set, the keys are sorted alphabetically, which guarantees the same output every time (python key order is random)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.