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


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

    学习日志2

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

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

    1. python_str={
    2. "season":
    3. [
    4. {"spring":{"fruit":"pineapple"}},
    5. {"summer":{"fruit":["watermelon","peach"]}},
    6. {"fall":{"fruit": "apple"}},
    7. {"winter":{"fruit": "orange"}}
    8. ]
    9. }

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

    1. json_str=json.dumps(python_str)
    2. #输出
    3. {"season": [{"spring": {"fruit": "pineapple"}}, {"summer": {"fruit": ["watermelon", "peach"]}}, {"fall": {"fruit": "apple"}}, {"winter": {"fruit": "orange"}}]}

            2.1格式化输出

    1. json_str=json.dumps(python_str,sort_keys=True,indent=3)
    2. print(json_str)
    3. #输出
    4. {
    5. "season": [
    6. {
    7. "spring": {
    8. "fruit": "pineapple"
    9. }
    10. },
    11. {
    12. "summer": {
    13. "fruit": [
    14. "watermelon",
    15. "peach"
    16. ]
    17. }
    18. },
    19. {
    20. "fall": {
    21. "fruit": "apple"
    22. }
    23. },
    24. {
    25. "winter": {
    26. "fruit": "orange"
    27. }
    28. }
    29. ]
    30. }
    31. 进程已结束,退出代码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()方法)

    1. python_str=json.loads(json_str)
    2. #输出
    3. {'season': [{'spring': {'fruit': 'pineapple'}}, {'summer': {'fruit': ['watermelon', 'peach']}}, {'fall': {'fruit': 'apple'}}, {'winter': {'fruit': 'orange'}}]}

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

    1. python_str=json.load(open("./json.file.json","r"))
    2. print(python_str)
    3. #输出
    4. {'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文件:

     转换代码:

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

    输出:

             6.2 json文件转化为xml文件

    转换代码:

    1. import json
    2. import xmltodict
    3. def json_to_xml(python_dir):
    4. xml_str=xmltodict.unparse(python_dir)
    5. return xml_str
    6. json_path="./1.jsonfile.json"
    7. f=open(json_path,"r")
    8. json_file=f.read()
    9. python_dir=json.loads(json_file)
    10. with open("./2.xml","w") as fp:
    11. fp.write(json_to_xml(python_dir))
    12. #原内容
    13. {
    14. "action": {
    15. "@year": "3/08/2022",
    16. "season": [
    17. "summer",
    18. "winter"
    19. ],
    20. "incident": "miss"
    21. }
    22. }
    23. #写入xml文件内容
    24. "1.0" encoding="utf-8"?>
    25. "3/08/2022">summerwintermiss

    7.json字符串解析

    1. import json
    2. python_str={
    3. "season":
    4. [
    5. {"spring":[{"fruit":"pineapple"}]},
    6. {"summer":[{"fruit":["watermelon","peach"]}]},
    7. {"fall":[{"fruit": "apple"}]},
    8. {"winter":[{"fruit": "orange"}]}
    9. ]
    10. }
    11. #定位数据节点
    12. #打印字典所有key
    13. print(python_str.keys())
    14. #打印字典所有value
    15. print(python_str.values())
    16. print(python_str["season"][0])
    17. print(python_str["season"][1])
    18. #输出
    19. dict_keys(['season'])
    20. dict_values([[{'spring': [{'fruit': 'pineapple'}]}, {'summer': [{'fruit': ['watermelon', 'peach']}]}, {'fall': [{'fruit': 'apple'}]}, {'winter': [{'fruit': 'orange'}]}]])
    21. {'spring': [{'fruit': 'pineapple'}]}
    22. {'summer': [{'fruit': ['watermelon', 'peach']}]}

     8.解析json文件

    1. import json
    2. # 1、JSON文件转换为Python对象
    3. python_obj = json.load(open('test.json', 'r'))
    4. print(python_obj)
    5. print(type(python_obj))
    6. print("-" * 20)
    7. # 2、解析json文件
    8. # 输出cours节点e下的数据
    9. print(python_obj['student']['course']['name']) # 输出name
    10. print(python_obj['student']['course']['score']) # 输出score
    11. # 输出info节点下的数据
    12. print(python_obj['student']['info']['sex']) # 输出sex
    13. print(python_obj['student']['info']['name']) # 输出name
    14. # 输出stid节点下的数据
    15. print(python_obj['student']['stid']) # 输出stid

  • 相关阅读:
    【FPGA】Verilog语言从零到精通
    appliedzkp zkevm(9)中的Bytecode Proof
    「Android」孙正义|窥探OKHttp+Gson
    VS2010 Windows API 串口编程 (一)
    朋友圈早上好问候语,祝福朋友健康幸福,情谊久久!
    设计模式学习笔记(四)单例模式的实现方式和使用场景
    一次清理全屋地面,一键清洁烘干无异味,KEEWOO启为C260 Pro洗地机上手
    Qt获取屏幕(桌面)的大小或分辨率
    【深度学习】argparse模块一些学习心得体会(2)| parser.parse_known_args() |位置参数 可选参数
    【C++深度探索】全面解析多态性机制(二)
  • 原文地址:https://blog.csdn.net/weixin_62599885/article/details/126143079