原文:
https://blog.csdn.net/dl1456074580/article/details/86538098
pythondef skip_ws(txt, pos):
while pos < len(txt) and txt[pos].isspace():
pos += 1
return pos
def parse_str(txt, pos, allow_ws=False, delimiter=[',', ':', '}', ']']):
while pos < len(txt):
if not allow_ws and txt[pos].isspace():
break
if txt[pos] in delimiter:
break
pos += 1
return pos
def parse_obj(txt, pos):
obj = dict()
while True:
pos = skip_ws(txt, pos + 1)
end = parse_str(txt, pos, True, [':'])
if end >= len(txt):
raise ValueError("unexpected end when parsing object key")
key = txt[pos:end].strip()
pos = skip_ws(txt, end + 1)
if pos >= len(txt):
raise ValueError("unexpected end when parsing object value")
if txt[pos] == '[':
value, pos = parse_array(txt, pos)
elif txt[pos] == '{':
value, pos = parse_obj(txt, pos)
else:
end = parse_str(txt, pos, True, [',', '}'])
if end >= len(txt):
raise ValueError("unexpected end when parsing object value")
value = txt[pos:end].strip()
pos = end
obj[key] = value
pos = skip_ws(txt, pos)
if pos >= len(txt):
raise ValueError("unexpected end when object value finish")
if txt[pos] == '}':
return obj, pos + 1
def parse_array(txt, pos):
array = list()
while True:
pos = skip_ws(txt, pos + 1)
if pos >= len(txt):
raise ValueError("unexpected end when parsing array item")
if txt[pos] == '[':
value, pos = parse_array(txt, pos)
elif txt[pos] == '{':
value, pos = parse_obj(txt, pos)
else:
end = parse_str(txt, pos, True, [',', ']'])
if end >= len(txt):
raise ValueError("unexpected end when parsing array item")
value = txt[pos:end].strip()
pos = end
array.append(value)
pos = skip_ws(txt, pos)
if pos >= len(txt):
raise ValueError("unexpected end when array item finish")
if txt[pos] == ']':
return array, pos + 1
def parse(txt):
if txt.startswith('json'):
pos = txt.find(':')
if pos != -1:
pos = skip_ws(txt, pos + 1)
if txt[pos] == '{':
obj, pos = parse_obj(txt, pos)
return obj
elif txt[pos] == '[':
array, pos = parse_array(txt, pos)
return array
raise ValueError("format error when parsing root")
if __name__ == '__main__':
import json
txt = r'json:{name:张三,age:22,book:[{bookname:语文,booksize:200,soce:100},{wkke:123}]}'
resdict = parse(txt)
print(resdict)
print(type(resdict))
restxt=json.dumps(resdict,ensure_ascii=False)
print(restxt)
print(type(restxt))
resd=json.loads(restxt)
print(resd)
print(type(resd))
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!