alex_bn_lee

导航

[981] JSON module in Python

In Python, the json module provides functions for encoding and decoding JSON data. Here's a brief explanation of the commonly used functions:

  1. json.dump() and json.load() are functions for file processing.
  2. json.dumps() and json.loads() are functions for variable processing.
  3. dump(s): dict -> string
  4. load(s): string -> dict

  1. json.dumps(): This function is used to serialize Python objects to a JSON formatted string. It takes a Python object (such as a dictionary or a list) as input and returns a JSON formatted string.

    Example:

    import json
    
    data = {'name': 'John', 'age': 30, 'city': 'New York'}
    json_string = json.dumps(data)
    print(json_string)
  2. json.dump(): This function is similar to json.dumps(), but it writes the JSON data directly to a file-like object (such as a file object opened in write mode). It serializes the Python object to JSON and writes it to the specified file.

    Example:

    import json
    
    data = {'name': 'John', 'age': 30, 'city': 'New York'}
    with open('data.json', 'w') as json_file:
        json.dump(data, json_file)
  3. json.loads(): This function is used to deserialize a JSON formatted string into a Python object. It takes a JSON formatted string as input and returns a Python object (such as a dictionary or a list).

    Example:

    import json
    
    json_string = '{"name": "John", "age": 30, "city": "New York"}'
    data = json.loads(json_string)
    print(data)
  4. json.load(): This function is similar to json.loads(), but it reads JSON data from a file-like object (such as a file object opened in read mode) and deserializes it into a Python object.

    Example:

    import json
    
    with open('data.json', 'r') as json_file:
        data = json.load(json_file)
    print(data)

These functions are commonly used when working with JSON data in Python, allowing you to serialize Python objects to JSON format and vice versa.

posted on 2024-02-26 06:49  McDelfino  阅读(1)  评论(0编辑  收藏  举报