有这样一组JSON字符串:
json_str = ''' { "school": { "students": [ { "name": "小明", "age": 12, "sex": "male" }, { "name": "小红", "age": 13, "sex": "female" }, { "name": "小强", "age": 14, "sex": "male" } ], "school_name": "光明中学", "manager": "大强", "age": 100 } } '''
如果您需要获取所有学生的年龄,您是不是会用【import json】或者其他JSON库解析此JSON字符串呢,现在有种更简单的方式了呦~
首先,安装UniversalParser:
pip install UniversalParser
继续上面的代码:
import UniversalParser as UP # json_data 是 JSON 字符串 manager = UP.parse_json(json_data, analysis_text=False) # 获取所有学生的年龄 students_age = manager | 'students' | 'age' print([_age & UP.SM.text for _age in students_age]) # [12, 13, 14] # 获取学校的年龄 print(manager.document.school.age) # 100 # 遍历所有的学生 for stu in manager | 'students': print(stu.name, stu.age, stu.sex) ''' output: 小明 12 male 小红 13 female 小强 14 male ''' manager.save_as_xml() # 保存为 XML
如果您觉得此方法可以,可以查看具体的教程:JSON - Universal Parser