马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
1. 标题
分析json格式的字符串,并将其转成字典格式。
2. 分析
这是一道必要用递归的标题。
有几个地方必要留意:
- 知道 json 格式的字符串长什么样子
- 知道 该用递归的方式写题,递归处置处罚的是新的字符串,传入下层栈的字符串得遍历获取。
3. 代码
- # 将json字符串解析成字典对象
- def parse_json_to_dict(s):
- # print(s)
- res = {}
- key = "" # 初始化为空
- value = ""
- flag_of_colon = 0
- i = 0
- while(i < len(s)):
- cur_char = s[i]
- # print(i, cur_char)
- if i == 0 or cur_char== " " or cur_char == '"' or cur_char=="}":
- i += 1
- continue
- else:
- # 如果不是从0位开始,且该位是{
- if cur_char == "{":
- # 找到下一个匹配的}下标
- j = i
- cnt = 0 # {的个数
- target = s[j]
- while(j < len(s)):
- if target == "{":
- cnt += 1
- elif target == "}":
- cnt -= 1
- j += 1
- if cnt == 0:
- break
- target = s[j]
- new_s = s[i:j]
- tmp = parse_json_to_dict(new_s)
- # print("tmp = ", tmp)
- # print("key = ", key)
- res[key] = tmp
- key = ""
- i = j
- continue
- elif cur_char == ":": # 开始换
- flag_of_colon = 1
- elif cur_char == ",": # 重置
- if len(key) and len(value):
- res[key] = value
- flag_of_colon = 0
- key = ""
- value = ""
- else:
- if flag_of_colon:
- value = value + cur_char
- else:
- key = key + cur_char
- i += 1
- if len(key) and len(value):
- res[key] = value
- return res
- s = """{"name":"liushen", "age":"28"}"""
- # s = """{"name":"liushen", "other":{"age":"28"}}"""
- # s = """{"name":"liushen", "other":{"o2":{"sex":"male"}}, "school":{"abc":"ecnu"}}"""
- res = parse_json_to_dict(s)
- print(res)
复制代码 |