您当前的位置: 首页 >  Python

Bulut0907

暂无认证

  • 6浏览

    0关注

    346博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python json的详细使用讲解

Bulut0907 发布时间:2020-11-16 12:13:45 ,浏览量:6

目录
  • 1. import json
  • 2. dict转str
  • 3. json格式的str转dict
  • 4. 保存数据到文件,再从文件中读取数据

1. import json
import json
2. dict转str
map = {"键1":"值1", "键2":"值2"}

str1 = json.dumps(map)
print(str1)             # {"\u952e1": "\u503c1", "\u952e2": "\u503c2"}

str2 = json.dumps(map, ensure_ascii = False)
print(str2)             # {"键1": "值1", "键2": "值2"}

默认是使用ascii编码,这样中文无法阅读,所有使用ensure_ascii = False关闭ascii

3. json格式的str转dict
json_str='{"键1": "值1", "键2": "值2"}'

map = json.loads(json_str)
print(type(map))            # 
print(map)                  # {'键1': '值1', '键2': '值2'}
4. 保存数据到文件,再从文件中读取数据

文件不一定是.json类型的

import os
import json

if __name__ == '__main__':

    names = ['zhang_san', 'li_si', 'wang_wu']
    file_path = os.getcwd() + r'/test.txt'
    
    with open(file_path, 'w', encoding='utf-8') as f:
        # 将数据导入到文件中
        json.dump(names, f)

    with open(file_path, 'r', encoding='utf-8') as f:
        # 从文件中加载数据
        read_content = json.load(f)
        print(read_content)             # ['zhang_san', 'li_si', 'wang_wu']

test.txt文件内容如下:

["zhang_san", "li_si", "wang_wu"]
关注
打赏
1664501120
查看更多评论
立即登录/注册

微信扫码登录

0.0435s