user8471763
user8471763

Reputation:

Reading and Writing JSON through Python

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.

Upvotes: 9

Views: 25302

Answers (2)

Vikash Singh
Vikash Singh

Reputation: 14001

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)

Upvotes: 20

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

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)

Upvotes: 5

Related Questions