Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(", ", ", '"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading