Python21天学习挑战赛Day(3-4)·json标准库(应用)

活动地址:CSDN21天学习挑战赛

学习日志2

        这节内容学习了JSON基础概述,JSON模块,XML文件与JSON文件互转,解析JSON文件。现在进行复盘及应用。

1.新建一个python对象(字典)

python_str={
	"season":
	[
		{"spring":{"fruit":"pineapple"}},
		{"summer":{"fruit":["watermelon","peach"]}},
		{"fall":{"fruit": "apple"}},
        {"winter":{"fruit": "orange"}}
    ]
}

2.将python字典转化为json字符串(json.dumps()方法)

​
json_str=json.dumps(python_str)

#输出
{"season": [{"spring": {"fruit": "pineapple"}}, {"summer": {"fruit": ["watermelon", "peach"]}}, {"fall": {"fruit": "apple"}}, {"winter": {"fruit": "orange"}}]}

​

        2.1格式化输出

json_str=json.dumps(python_str,sort_keys=True,indent=3)
print(json_str)

#输出
{
   "season": [
      {
         "spring": {
            "fruit": "pineapple"
         }
      },
      {
         "summer": {
            "fruit": [
               "watermelon",
               "peach"
            ]
         }
      },
      {
         "fall": {
            "fruit": "apple"
         }
      },
      {
         "winter": {
            "fruit": "orange"
         }
      }
   ]
}

进程已结束,退出代码0

 3.将python字典转化为json字符串并存入json文件中(json.dump()方法)

        3.1新建一个空的json文件

        3.2转换并写入json文件中

json.dump(python_str,open("./json.file.json","w"),sort_keys=True,indent=3)

         存储结果:

 4.将json格式的字符串转换为python类型(json.loads()方法)

​
python_str=json.loads(json_str)

​
#输出
{'season': [{'spring': {'fruit': 'pineapple'}}, {'summer': {'fruit': ['watermelon', 'peach']}}, {'fall': {'fruit': 'apple'}}, {'winter': {'fruit': 'orange'}}]}

5.从json格式文件中读取数据转化为python类型(json.load()方法)

python_str=json.load(open("./json.file.json","r"))
print(python_str)
#输出
{'season': [{'spring': {'fruit': 'pineapple'}}, {'summer': {'fruit': ['watermelon', 'peach']}}, {'fall': {'fruit': 'apple'}}, {'winter': {'fruit': 'orange'}}]}

 6.XML文件与json文件转化

安装模块——

pip install xmltodict

        6.1 xml文件转为json文件

新建一个1.xml文件:

 转换代码:

import json
import xmltodict
def xml_to_json(xml_str):
	xml_parse=xmltodict.parse(xml_str)
	json_str=json.dumps(xml_parse,indent=2)
	return json_str
xml_path='./1.xml'
f=open(xml_path,"r")
xml_file=f.read()
with open('./1.jsonfile.json',"w") as newf:
	newf.write(xml_to_json(xml_file))

输出:

         6.2 json文件转化为xml文件

转换代码:

import json
import xmltodict
def json_to_xml(python_dir):
	xml_str=xmltodict.unparse(python_dir)
	return xml_str

json_path="./1.jsonfile.json"
f=open(json_path,"r")
json_file=f.read()
python_dir=json.loads(json_file)
with open("./2.xml","w") as fp:
	fp.write(json_to_xml(python_dir))

#原内容
{
  "action": {
    "@year": "3/08/2022",
    "season": [
      "summer",
      "winter"
    ],
    "incident": "miss"
  }
}
#写入xml文件内容
<?xml version="1.0" encoding="utf-8"?>
<action year="3/08/2022"><season>summer</season><season>winter</season><incident>miss</incident></action>

7.json字符串解析

import json
python_str={
	"season":
		[
		{"spring":[{"fruit":"pineapple"}]},
		{"summer":[{"fruit":["watermelon","peach"]}]},
		{"fall":[{"fruit": "apple"}]},
        {"winter":[{"fruit": "orange"}]}
		]
}
#定位数据节点
#打印字典所有key
print(python_str.keys())
#打印字典所有value
print(python_str.values())
print(python_str["season"][0])
print(python_str["season"][1])

#输出
dict_keys(['season'])
dict_values([[{'spring': [{'fruit': 'pineapple'}]}, {'summer': [{'fruit': ['watermelon', 'peach']}]}, {'fall': [{'fruit': 'apple'}]}, {'winter': [{'fruit': 'orange'}]}]])
{'spring': [{'fruit': 'pineapple'}]}
{'summer': [{'fruit': ['watermelon', 'peach']}]}

 8.解析json文件

import json

# 1、JSON文件转换为Python对象
python_obj = json.load(open('test.json', 'r'))
print(python_obj)
print(type(python_obj))

print("-" * 20)
# 2、解析json文件

# 输出cours节点e下的数据
print(python_obj['student']['course']['name'])  # 输出name
print(python_obj['student']['course']['score'])  # 输出score

# 输出info节点下的数据
print(python_obj['student']['info']['sex'])  # 输出sex
print(python_obj['student']['info']['name'])  # 输出name

# 输出stid节点下的数据
print(python_obj['student']['stid'])  # 输出stid

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linalw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值