Kevin Nguyen
Kevin Nguyen

Reputation: 105

what is different loads, dumps vs read json file?

I have a simple json file 'stackoverflow.json" { "firstname": "stack", "lastname": "overflow" }

what is different between 2 below functions:

def read_json_file_1():
    with open('stackoverflow.json') as fs:
        payload = ujson.loads(fs.read())
        payload = ujson.dumps(payload)
    return payload

def read_json_file_2():
    with open ('stackoverflow.json') as fs:
        return payload = fs.read()

Then I use 'requests' module to send post resquest with payload from 2 above funtions and it works for both.

Thanks.

Upvotes: 1

Views: 2760

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

the 'loads' function takes a json file and converts it into a dictionary or list depending on the exact json file. the `dumps' take a python data structure, and converts it back into json.

so you first function is loading and validating json, converting it into a python structure, and then converting it back to json before returning, whereas your 2nd function just reads the content of the file, with no conversion or validation

The functions are therefore only equivalent if the json is valid - if there are json errors then the two functions will execute very differently.If you know that the file contains an error free json the two files should return equivalent output, however if the file contains error within the json, then the first function will fail with relevant tracebacks etc, and the 2nd function wont generate any errors at all. The 1st function is more error friendly, but is less efficient (since it converts json -> python -> json). The 2nd function is much more efficient but is much less error friendly (i.e. it wont fail if the json is broken).

Upvotes: 3

Related Questions