Python:禁用模块时将JSON字符串转换为字典的实现求助
手动实现JSON到Python字典的解析(无模块依赖)
第一步:预处理JSON字符串
读取后的JSON字符串包含换行、缩进等空白字符,先写个工具函数跳过这些无关空白,同时保留字符串内部的空格:
def skip_whitespace(s, idx): while idx < len(s) and s[idx] in ' \n\t\r': idx += 1 return idx
第二步:核心解析函数(递归处理嵌套结构)
下面是完整的解析实现,涵盖字符串、数字、嵌套字典的解析:
def parse_string(s, idx): idx += 1 # 跳过开头的" start = idx while idx < len(s): if s[idx] == '"' and (idx == 0 or s[idx-1] != '\\'): # 找到非转义的结束引号 return s[start:idx], idx + 1 idx += 1 raise ValueError("未闭合的字符串") def parse_number(s, idx): start = idx while idx < len(s) and s[idx] in '0123456789.-+': idx += 1 num_str = s[start:idx] if '.' in num_str: return float(num_str), idx else: return int(num_str), idx def parse_object(s, idx): obj = {} idx += 1 # 跳过开头的{ idx = skip_whitespace(s, idx) while idx < len(s) and s[idx] != '}': # 解析键 key, idx = parse_string(s, idx) idx = skip_whitespace(s, idx) if idx >= len(s) or s[idx] != ':': raise ValueError("缺少冒号分隔键值") idx += 1 idx = skip_whitespace(s, idx) # 解析值(递归调用主解析函数) value, idx = parse_json(s, idx) obj[key] = value idx = skip_whitespace(s, idx) if idx < len(s) and s[idx] == ',': idx += 1 idx = skip_whitespace(s, idx) idx += 1 # 跳过结束的} return obj, idx def parse_json(s): idx = skip_whitespace(s, 0) if idx >= len(s): return None if s[idx] == '{': return parse_object(s, idx)[0] elif s[idx] == '"': return parse_string(s, idx)[0] elif s[idx] in '0123456789.-+': return parse_number(s, idx)[0] else: raise ValueError(f"无法识别的字符: {s[idx]}")
第三步:结合你的文件读取流程使用
把读取后的字符串传入解析函数即可:
# 读取文件并解码 with open('test.json', 'rb') as file: myfile = file.read() json_str = str(myfile, 'ascii') # 解析为Python字典 result_dict = parse_json(json_str) print(result_dict) print(type(result_dict)) # 输出 <class 'dict'>
适配你的示例JSON
用你提供的JSON字符串测试,会得到对应的嵌套字典,比如result_dict["task0"]["task_id"]会返回0。如果需要支持数组、布尔值、null等其他JSON类型,可以扩展对应的解析分支。
内容的提问来源于stack exchange,提问作者Luca Minutillo
相关产品推荐
相关产品推荐

