-1

I have wrote a code like below -

>>> text = "ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ \"АПК\" \"РАССВЕТ\""
>>> text = text.replace('"', '\"').replace("'", "\'")
>>> data = '{"text": "' + str(text) + '"}'
>>> print(data)
{"text": "ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "АПК" "РАССВЕТ""}
>>> final_data = json.loads(data)

json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 53 (char 52)

Do we have any other way to make the double quotes parsed in json.loads ? Help me out please.

deepu2711
  • 59
  • 1
  • 7

1 Answers1

0

As suggested in the comments, you can write your JSON object and then use json.dumps() to get the string, but if you really want to manually write the JSON as a string and then load it with json.loads():

data = """{ "text": "%s" }""" % text.replace('\"', '\\"').replace("'", "\\'")
json.loads(data)  # {'text': 'ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "АПК" "РАССВЕТ"'}

With json.dumps():

json.dumps({"text": text}, ensure_ascii=False)
# '{"text": "ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ \\"АПК\\" \\"РАССВЕТ\\""}'
Jonathan Ciapetti
  • 1,261
  • 3
  • 11
  • 16
  • If we have a list - text = ['ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "АПК" "РАССВЕТ"', 'LIMITED LIABILITY COMPANY "APK" "RASSVET"'] , how to parse this using json.loads ?https://stackoverflow.com/users/6273711/user – deepu2711 Jul 14 '22 at 06:22
  • If I answered your question, please consider accepting my answer. As for your doubt, the string now would simply be the first element of `text`, ie: `json_loads(text[0])` – Jonathan Ciapetti Jul 14 '22 at 13:30