python How to Write a Dictionary as an json File

  • 2021-12-04 10:33:54
  • OfStack

Directory python writes dictionary as json file dictionary structure as follows writes jsonPython txt file read write dictionary (json, eval) uses json conversion method uses str conversion method

python writes the dictionary as an json file

The dictionary structure is as follows


res = {
    "data":[]
}
temp = {
        "name":name,
        "cls":cls
}
res["data"].append(temp)

Write json

The specific code is as follows:


json_data = json.dumps(res)
with open('E:/res.json', 'a') as f_six:
    f_six.write(json_data)

Requirements can be completed ~ ~

Python txt File Read and Write Dictionary (json, eval)

Use the json conversion method

1. The dictionary is written into txt


import json
dic = {  
    'andy':{  
        'age': 23,  
        'city': 'beijing',  
        'skill': 'python'  
    },  
    'william': {  
        'age': 25,  
        'city': 'shanghai',  
        'skill': 'js'  
    }  
}  
js = json.dumps(dic)   
file = open('test.txt', 'w')  
file.write(js)  
file.close()  

2. Read the dictionary in txt


import json
file = open('test.txt', 'r') 
js = file.read()
dic = json.loads(js)   
print(dic) 
file.close() 

Use the str conversion method

1. The dictionary is written into txt


dic = {  
    'andy':{  
        'age': 23,  
        'city': 'beijing',  
        'skill': 'python'  
    },  
    'william': {  
        'age': 25,  
        'city': 'shanghai',  
        'skill': 'js'  
    }  
} 
fw = open("test.txt",'w+')
fw.write(str(dic))      # Convert a dictionary into str
fw.close()

2. Read the dictionary in txt


fr = open("test.txt",'r+')
dic = eval(fr.read())   # Read str Convert to a dictionary 
print(dic)
fr.close()

Related articles: