Home > Software design >  how to convert string to dict with double quotes in python?
how to convert string to dict with double quotes in python?

Time:09-17

i want to convert string to dict with double quotes

here is example

"{'a':'b'}"

i tried replace with json.dumps but it is not resolved

a = "{'a':'b'}"
b = a.replace("'", "\"") # '{"id":"b"}'
c = json.dumps(c, ensure_ascii=False) # '"{\"id\\":\"b\"}"'

i want to solve like this

{"a":"b"}

how can i solve it?

CodePudding user response:

That's not JSON.

>>> import json
>>> foo = "{'a':'b'}"
>>> json.loads(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

But it does look a lot like python

>>> import ast
>>> ast.literal_eval(foo)
{'a': 'b'}

Whether this works for you depends on where this string came from and what its serialization rules are.

CodePudding user response:

json.dumps takes a structure and dumps it as JSON. You want json.loads, which takes a JSON string and loads it into a structure.

>>> json.loads(a.replace("'", '"'))
{'a': 'b'}

CodePudding user response:

Based on the single quotes in a, it's more likely a Python dict than a JSON object, so you probably want ast.literal_eval() instead.

>>> import ast
>>> a = "{'a':'b'}"
>>> ast.literal_eval(a)
{'a': 'b'}
  • Related