Python處理json字典與字符串的轉換

import json

"""
dumps:將python中的字典轉換爲字符串
output:
    <class 'dict'>
    {'fontFamily': '微軟雅黑', 'fontSize': 12, 'BaseSettings': {'font': 1, 'size': {'length': 40, 'wigth': 30}}}
    <class 'str'>
    {"fontFamily": "\u5fae\u8f6f\u96c5\u9ed1", "fontSize": 12, "BaseSettings": {"font": 1, "size": {"length": 40, "wigth": 30}}}
"""


def json_dumps():
    json_dict = {'fontFamily': '微軟雅黑', 'fontSize': 12, 'BaseSettings': {'font': 1, 'size': {'length': 40, 'wigth': 30}}}
    print(type(json_dict))
    print(json_dict)
    json_str = json.dumps(json_dict)
    print(type(json_str))
    print(json_str)


"""
dump:將數據寫入json文件中
"""


def json_dump():
    json_dict = {'fontFamily': '微軟雅黑', 'fontSize': 12, 'BaseSettings': {'font': 1, 'size': {'length': 40, 'wigth': 30}}}
    with open("../file/record.json", "w")as f:
        json.dump(json_dict, f)
        print("finished")


"""
loads:將字符串轉換爲字典
output:
    <class 'str'>
    {"fontFamily": "微軟雅黑", "fontSize": 12, "BaseSettings": {"font": 1, "size": {"length": 40, "wigth": 30}}}
    <class 'dict'>
    {'fontFamily': '微軟雅黑', 'fontSize': 12, 'BaseSettings': {'font': 1, 'size': {'length': 40, 'wigth': 30}}}
"""


def json_loads():
    json_str = '{"fontFamily": "\u5fae\u8f6f\u96c5\u9ed1", "fontSize": 12, "BaseSettings": {"font": 1, "size": {"length": 40, "wigth": 30}}}'
    print(type(json_str))
    print(json_str)
    json_dict = json.loads(json_str)
    print(type(json_dict))
    print(json_dict)


"""
load:讀文件,並把字符串變換爲Python數據類型
output:
    40
    {'fontFamily': '微軟雅黑', 'fontSize': 12, 'BaseSettings': {'font': 1, 'size': {'length': 40, 'wigth': 30}}}
"""


def json_load():
    f = open("../file/record.json", encoding='utf-8')
    setting = json.load(f)
    print(setting['BaseSettings']['size']['length'])
    setting['BaseSettings']['size']['length'] = 40
    print(setting)


if __name__ == '__main__':
    json_dumps()
    json_dump()
    json_loads()
    json_load()
相關文章
相關標籤/搜索