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.
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(", ", ", '"))
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.
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(", ", ", '"))