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

Question:

I want to convert the string '{x:=1, y=2, z=3}' to a Python object. I tried json.loads(), but got an error, it was expecting string to be '{"x":1, "y":2, "z":3}'.

I’m new to Python, if anyone can help that would be great.

Asked By: the_tech_guy

||

Answers:

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(", ", ", '"))
Answered By: Lorenz Hetterich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.