Python读写json文件的方法(基于自带的json模块)


"""
!python 3, to read and write json data.
python type <-> json type
-------------------------------------
| python                | json      |
|-----------------------|-----------|
| dict                  | object    |
| list, tuple           | array     |
| str, unicode          | string    |
| int, long, float      | number    |
| True                  | true      |
| False                 | false     |
| None                  | null      |
-------------------------------------
json module provides four methods:
- dump: serialize string into json and write it in a file.
- dumps: serialize string
- load: read a file and deserialize json into string.
- loads: deserialize json into string
"""
import json


def get_data_from_json_file(filepath: str) -> {}:
    with open(filepath, 'r', encoding='utf-8') as f:
        data = json.loads(f.read())
    f.close()
    '''output!'''
    print(data)  # the output could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
    for key in data.keys():
        print(f'{key}={data[key]}')
        # the output could be
        # a=100
        # b=bba
        # c={'a': 100, 'b': 200}
    print('read done!')


def get_data_from_json_file1(filepath: str) -> {}:
    with open(filepath, 'r', encoding='utf-8') as f:
        data = json.load(f)
    print(data)  # the output could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
    '''output!'''
    for key in data.keys():
        print(f'{key}={data[key]}')
        # the output could be
        # a=100
        # b=bba
        # c={'a': 100, 'b': 200}
    print('read done!')


def put_data_into_json_file(filepath: str, content: {}):
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(json.dumps(content, indent=4))
        # the content could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
        # in the json file, it shows:
        # {
        #   "a": 100,
        #   "b": "bba",
        #   "c": {
        #       "a": 100,
        #       "b": 200
        #   }
        # }
    print('write done!')


def put_data_into_json_file1(filepath: str, content: {}):
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(content, f, indent=4)
        # the content could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
        # in the json file, it shows:
        # {
        #   "a": 100,
        #   "b": "bba",
        #   "c": {
        #       "a": 100,
        #       "b": 200
        #   }
        # }
    print('write done!')