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

前端 未结 6 774
天涯浪人
天涯浪人 2020-11-29 16:36

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

I guess that the load() function must be used with a file

6条回答
  •  伪装坚强ぢ
    2020-11-29 17:03

    Just going to add a simple example to what everyone has explained,

    json.load()

    json.load can deserialize a file itself i.e. it accepts a file object, for example,

    # open a json file for reading and print content using json.load
    with open("/xyz/json_data.json", "r") as content:
      print(json.load(content))
    

    will output,

    {u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
    

    If I use json.loads to open a file instead,

    # you cannot use json.loads on file object
    with open("json_data.json", "r") as content:
      print(json.loads(content))
    

    I would get this error:

    TypeError: expected string or buffer

    json.loads()

    json.loads() deserialize string.

    So in order to use json.loads I will have to pass the content of the file using read() function, for example,

    using content.read() with json.loads() return content of the file,

    with open("json_data.json", "r") as content:
      print(json.loads(content.read()))
    

    Output,

    {u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
    

    That's because type of content.read() is string, i.e.

    If I use json.load() with content.read(), I will get error,

    with open("json_data.json", "r") as content:
      print(json.load(content.read()))
    

    Gives,

    AttributeError: 'str' object has no attribute 'read'

    So, now you know json.load deserialze file and json.loads deserialize a string.

    Another example,

    sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,

    cat json_data.json | ./test.py
    
    {u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
    

    If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.

提交回复
热议问题