Convert string like '{x:=1, y=2, z=3}' to JSON in python


data = ‘{x:=1, y=2, z=3}’
I want to convert the above string to python,

i tried json.loads(), but it was giving error, it was expecting string to be ‘{"x":1, "y":2, "z":3}’

I’m new in python, if anyone can help that would be great.

>Solution :

you may want to try to parse the string yourself:

def parse_input(x):
    result = dict()
    x = x.replace(":", "")
    for pair in x[1:-1].split(","):
        key,value = tuple(pair.split("="))
        result[key.strip()] = int(value.strip())
    return result

Alternatively, you can convert the string to be valid json and then load it:

obj = json.loads(data.replace("{", '{"').replace(":", "").replace("=", '":').replace(", ", ', "'))

If you want an evil solution that "works", here you go:

However, only use this, if the input is 100% trusted (as it uses eval).
Also, this will only work for inputs exactly matching your example.

obj = eval(data.replace("{", "{'").replace(":", "").replace("=", "':").replace(", ", ", '"))

Leave a ReplyCancel reply