json模块

json是种通用数据类型 ,json就是字符串,所有语言都可以解析

{
    "name": "xiaohei",
    "cars": [
        1,
        2,
        3
    ],
    "house": [
        4,
        5,
        6
    ],
    "tt": "哈哈"
}

python中json和dict可以互转

由json转dict用loads,eg:

import json #json只有双引号
json_str ='{"name": "xiaohei", "cars":"bmw"}'
dic1 = json.loads(json_str)
print(dic1)

由dict转json用dumps,eg:

import json #json只有双引号
d = {
    'name':'xiaohei',
    'cars':[1,2,3],
    'house':(4,5,6),
    'tt':'哈哈'
}

result = json.dumps(d,indent=4,ensure_ascii=False)#python转json的(list、tuple、dict)
print(result)
print(type(result))

将文件中的json读出来成字典用load

info.txt:

import json

with open('info.txt',encoding='utf-8') as fr: re = json.load(fr)#简化了写和转字典 print(re) print(type(re))
   #与前面相同功能 res
= fr.read() re = json.loads(res) print(re) print(type(re))

将字典转成json存入文件中用dump

import json
d = {
'name':'xiaohei',
'cars':[1,2,3],
'house':(4,5,6),
'tt':'哈哈'
}
#转成字符串写入文件
with open('info.json','w',encoding='utf-8') as fw:
    json.dump(d,fw,indent=4,ensure_ascii=False)#等同下两行

    # result = json.dumps(d, indent=4, ensure_ascii=False)
    # fw.write(result)
原文地址:https://www.cnblogs.com/Mezhou/p/13580037.html