Reading and Writing JSON through Python

前端 未结 2 1102
予麋鹿
予麋鹿 2020-12-06 20:30

read.json file :

{
    \"Username\" : \"admin\",
    \"Password\" : \"admin\",
    \"Iterations\" : 5,
    \"Decimal\" : 5.5,
    \"tags\" : [\"hello\", \"b         


        
相关标签:
2条回答
  • 2020-12-06 20:53

    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)
    0 讨论(0)
  • 2020-12-06 21:06

    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)
    
    0 讨论(0)
提交回复
热议问题