0

I am trying to run the below code which converts JSON string to Python dict:

test = """
{"t":"\""}
"""
a=json.loads(test)

When I try to run this code it gives:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [45], in <cell line: 4>()
      1 test = """
      2 {"t":"\""}
      3 """
----> 4 a=json.loads(test)
      5 a

File /usr/local/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    341     s = s.decode(detect_encoding(s), 'surrogatepass')
    343 if (cls is None and object_hook is None and
    344         parse_int is None and parse_float is None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:
    348     cls = JSONDecoder

File /usr/local/lib/python3.9/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    335 
    336     """
--> 337     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338     end = _w(s, end).end()
    339     if end != len(s):

File /usr/local/lib/python3.9/json/decoder.py:353, in JSONDecoder.raw_decode(self, s, idx)
    344 """Decode a JSON document from ``s`` (a ``str`` beginning with
    345 a JSON document) and return a 2-tuple of the Python
    346 representation and the index in ``s`` where the document ended.
   (...)
    350 
    351 """
    352 try:
--> 353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
    355     raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting ',' delimiter: line 2 column 8 (char 8)

whereas:

test = """
{
  "t":"jjlsjdlk"
}
"""
a=json.loads(test)

works well. How to escape the quotes character?

Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • you added one more `"` ? in your code `{"t":"\""}` – Aladin May 03 '22 at 10:00
  • `test` is `'\n{"t":"""}\n'`, which is **not** valid JSON. If you want the _actual backslash_ in the resulting string, you have to escape _that_, not the quote (or use a `r"aw string"`). But where is the string actually coming from, surely you'd write the dictionary rather than writing then immediately parsing the string? – jonrsharpe May 03 '22 at 10:00
  • Can you check the question. In the below i have mentioned example which works also – Santhosh May 03 '22 at 10:07
  • 1
    Yes, the example that's valid JSON works and the one that isn't doesn't. But again you need to escape the _backslash_, not the quote, to make it valid JSON. Either way that's something that's covered in the docs, other posts here (e.g. https://stackoverflow.com/q/5997029/3001761), ... Without context it's unclear why this is happening at all, though. – jonrsharpe May 03 '22 at 10:09
  • thanks so `\"` should be `\\"`. Then it worked – Santhosh May 03 '22 at 10:18
  • That's one way, yes, but the underlying question (and the reason I want more context) is: why not just write `a = {'t': '"'}`? Why go through the loop with the JSON? If the goal is the valid JSON string, why not `test = json.dumps(a)`, rather than the other way around? – jonrsharpe May 03 '22 at 10:25

1 Answers1

-1

This is how you can escape the double quotes inside the value of "t"

test = r'{"t":"\""}'
a=json.loads(test)

If you really want multiline, use instead a simple string with double backslash:

test = '\
{\
"t": "\\""\
}\
'
a=json.loads(test)
nferreira78
  • 1,013
  • 4
  • 17