python - what is different loads, dumps vs read json file? -
i have simple json file 'stackoverflow.json" { "firstname": "stack", "lastname": "overflow" }
what different between 2 below functions:
def read_json_file_1(): open('stackoverflow.json') fs: payload = ujson.loads(fs.read()) payload = ujson.dumps(payload) return payload def read_json_file_2(): open ('stackoverflow.json') fs: return payload = fs.read()
then use 'requests' module send post resquest payload 2 above funtions , works both.
thanks.
the 'loads' function takes json file , converts dictionary or list depending on exact json file. `dumps' take python data structure, , converts json.
so first function loading , validating json, converting python structure, , converting json before returning, whereas 2nd function reads content of file, no conversion or validation
the functions therefore equivalent if json valid - if there json errors 2 functions execute differently.if know file contains error free json 2 files should return equivalent output, if file contains error within json, first function fail relevant tracebacks etc, , 2nd function wont generate errors @ all. 1st function more error friendly, less efficient (since converts json -> python -> json). 2nd function more efficient less error friendly (i.e. wont fail if json broken).
Comments
Post a Comment