You cannot access banned topics.
str = "Lindar = \"text=light, position = True\", num=10, check_condition=False, Timeout=1000"
如何处理成下边这样的 json 结构:
{
“Lindar": "text=light, position = True",
"num": 10,
"check_condition"="False",
"Timeout": 1000
}
格式怪怪的,如果没有特殊需求的话,建议直接用 json 库转,格式有略微不同的话,稍微调整下格式再转。
自己随便写了点转换的代码,不敢写下去了,再写就要造一个 json 库轮子了。。
import json
text = "Lindar = \"text=light, position = True\", num=10, check_condition=False, Timeout=1000"
def split_text(text: str) -> list[str]:
start = 0
pieces = []
is_in_string = False
for index, char in enumerate(text):
if char == "\"":
is_in_string = not is_in_string
if char == "," and not is_in_string:
pieces.append(text[start:index])
start = index + 1
# 添加最后一段
pieces.append(text[start:])
return pieces
def combine_key_value(pieces: list[str]) -> dict:
pairs = {}
for piece in pieces:
for index, char in enumerate(piece):
if char == "=":
key = piece[:index]
value = piece[index + 1:]
key = key.strip()
value = value.strip()
pairs[key] = value
break
return pairs
def type_convert(text):
pass
pieces = split_text(text)
pairs = combine_key_value(pieces)
print(json.dumps(pairs))
满足了我的要求,太感谢您了。split_text 的那个 for 循环解决了问题,十分感谢!
没事,我也是早上没事写点片段热热身,能解决您的问题真是极好的。