Python JSON 解析类示例 - 使用 json.loads() 转换 JSON 字符串
以下是一个简单的 JSON 解析类的示例,它使用 Python 的 json 模块来将 JSON 字符串转换为 Python 对象:
import json
class JSONParser:
def __init__(self, json_string):
self.json_string = json_string
def parse(self):
try:
json_data = json.loads(self.json_string)
return json_data
except ValueError as e:
print('Invalid JSON string: ', e)
return None
使用示例:
json_string = '{"name": "John", "age": 30, "city": "New York"}'
json_parser = JSONParser(json_string)
# 解析 JSON 字符串并返回 Python 对象
json_data = json_parser.parse()
# 打印结果
print(json_data['name']) # John
print(json_data['age']) # 30
print(json_data['city']) # New York
该类接收一个 JSON 字符串作为输入,然后使用 json 模块的 loads 函数将其转换为 Python 对象。如果 JSON 字符串无效,则会返回 None 并打印出错误消息。
请注意,此示例仅适用于简单的 JSON 对象。如果您需要处理类型嵌套的 JSON 字符串,则需要进行更多的转换和数据验证。
原文地址: https://www.cveoy.top/t/topic/nErF 著作权归作者所有。请勿转载和采集!