Difference between json.dump () and json.dumps () in python

1. Convert python data structure to json string (json.dumps ())

>>> import json
>>> data={'name':'pipi','age':18}
>>> json.dumps(data)
'{"name": "pipi", "age": 18}'

2. Convert the string in json format to python data structure (json.loads ())

>>> json_str='{"name": "pipi", "age": 18}'
>>> json.loads(json_str)
{'name': 'pipi', 'age': 18}

 3. Write the json object to the file (json.dump ())

data={'name':'pipi','age':18}
>>> with open("c:/Users/cale/json.txt",'w') as f:
    json.dump(data,f)

 

 4. Get the json object from the file

with open("c:/Users/cale/json.txt",'r') as f:
    data=json.load(f)

    
>>> data
{'name': 'pipi', 'age': 18}
>>> 

Note: If f.read () is used to obtain a string, not a json object

with open("c:/Users/cale/json.txt",'r') as f:
    data=f.read()

    
>>> data
'{"name": "pipi", "age": 18}'

 

Guess you like

Origin www.cnblogs.com/pipile/p/12718760.html