分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

14.json文件读取

发布时间:2023-09-06 02:16责任编辑:林大明关键词:jsjson
json文件读取
1.#读取jsonimport jsonstr=‘‘‘[ ???{ ???"name":"Tom", ???"gender":"male", ???"birth":"1997-12-13" ???}, ???{ ???"name": "Jerry", ???"gender": "male", ???"birth": "1998-10-18" ???}]‘‘‘#注意问题 ?json字符串的表示需要用双引号,否则loads()方法会解析失败print(type(str))data=json.loads(str)print(data)print(type(data))print(data[0][‘birth‘])

执行结果如图:

2.#读取jsonimport jsondata=[ ???{ ???‘name‘:‘Tom‘, ???‘gender‘:‘male‘, ???‘birth‘:‘1997-12-13‘ ???}, ???{ ???‘name‘: ‘Jerry‘, ???‘gender‘: ‘male‘, ???‘birth‘: ‘1998-10-18‘ ???}]# 将json对象转为字符串,然后调用文件的write()方法写入文本with open(‘data.json‘,‘w‘)as file: ???file.write(json.dumps(data))

运行结果如图:

3.#读取jsonimport jsondata=[ ???{ ???‘name‘:‘德玛西亚‘, ???‘gender‘:‘male‘, ???‘birth‘:‘1997-12-13‘ ???}, ???{ ???‘name‘: ‘Jerry‘, ???‘gender‘: ‘male‘, ???‘birth‘: ‘1998-10-18‘ ???}]#保存json格式,添加一个参数indent,代表缩进字符个数。#为了输出中文 指定参数 ensure_ascii=Falsewith open(‘data.json3‘,‘w‘)as file: ???file.write(json.dumps(data,indent=2)) ???# file.write(json.dumps(data,indent=2,ensure_ascii=False))

执行结果如图:

14.json文件读取

原文地址:https://www.cnblogs.com/lvjing/p/9708779.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved