pythonjsonpython-2.7

What is the difference between json.load() and json.loads() functions


In Python, what is the difference between json.load() and json.loads()?

I guess that the load() function must be used with a file object (I need thus to use a context manager) while the loads() function take the path to the file as a string. It is a bit confusing.

Does the letter "s" in json.loads() stand for string?


Solution

  • Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation.

    Simple example:

    with open("file.json") as f:
      data = json.load(f)  # ok
    
      data = json.loads(f)  # not ok, f is not a string but a file
    
    text = '{"a": 1, "b": 2}'  # a string with json encoded data
    data = json.loads(text)