Python 向大家请教一道题,一个字符串,如何处理成 json 结构?

knowway · October 21, 2021 · Last by frankxii replied at October 22, 2021 · 2099 hits

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
}

共收到 3 条回复 时间 点赞

格式怪怪的,如果没有特殊需求的话,建议直接用 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))

frankxii 回复

满足了我的要求,太感谢您了。split_text 的那个 for 循环解决了问题,十分感谢!

knowway 回复

没事,我也是早上没事写点片段热热身,能解决您的问题真是极好的。

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up