Python之相关操作

671 阅读1分钟

查看数据类型:type

a = 'demo'
print(type(a))

单引号str与dict之间的转换

单引号str转dict

import json
a = '{"a":1}'
print(json.loads(a)) # {'a':1}

dict转单引号str

import json
b = {'a':1}
print(json.dumps(b)) # '{"a":1}'

json文件操作

读取json文件中的所有内容

def read_json():
    json_file = 'demo.json'
    with open(json_file, 'r', encoding='utf8') as f:
        dict_data = json.load(f)
    print(type(dict_data)) # <class 'dict'>

把dict内容写入到json文件中

def write_json():
    data_dict = {"name": 11}
    with open("static/fonts/fonts111.json", 'w', encoding='utf8') as fp:
        json.dump(data_dict, fp, ensure_ascii=False)

dict与json之间的转换

dict 转 json

data_dict = {"a": 1, 'b': 222}
print(json.dumps(data_dict, ensure_ascii=False)) # {"a": 1, "b": 222}

注意:json采用双引号。而dict可以是双引号也可以是单引号。

json 转 dict

import json
a = '{"a":1}'
print(json.loads(a)) # {'a':1}