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

前端 未结 6 766
天涯浪人
天涯浪人 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 16:49

    The json.load() method (without "s" in "load") can read a file directly:

    import json
    with open('strings.json') as f:
        d = json.load(f)
        print(d)
    

    json.loads() method, which is used for string arguments only.

    import json
    
    person = '{"name": "Bob", "languages": ["English", "Fench"]}'
    print(type(person))
    # Output : 
    
    person_dict = json.loads(person)
    print( person_dict)
    # Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
    
    print(type(person_dict))
    # Output : 
    
    

    Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.

提交回复
热议问题