Код: Выделить всё
{"name": "John",
"description": "I'm just \"A BOY\" okay? He said \"Hello, World!\" to everyone.",
"remark": "\"This is a test\" he mentioned."}
Я чувствую, что попробовал каждое регулярное выражение под солнцем, чтобы нацелиться на эти экземпляры (но оставьте все остальные двойные кавычки без обратной косой черты) и замените их пустой строкой (функционально просто удалите их). Если у кого-нибудь есть советы, я буду признателен.
Моя реализация сейчас выглядит примерно так:
Код: Выделить всё
import re
# Example JSON string with single backslash escaped double quotes
json_string = '''
"name": "John",
"description": "I'm just \"A BOY\" okay? He said \"Hello, World!\" to everyone.",
"remark": "\"This is a test\" he mentioned."
'''
# Define a regular expression pattern to match \" within a string
pattern = r'\\"'
# Use re.sub to replace all occurrences of the pattern with an empty string
cleaned_string = re.sub(pattern, '', json_string)
print(cleaned_string)
Для справки, мне бы хотелось, чтобы результат был таким:
Код: Выделить всё
{"name": "John",
"description": "I'm just A BOY okay? He said Hello, World! to everyone.",
"remark": "This is a test he mentioned."}
Код: Выделить всё
"\"Girl Let's Talk\" Virtual 90s Kickback"
Код: Выделить всё
{"search_ads": [ {"event_id": "4838383", "ad_id": "1112", "budget_amount": 5.0, "currency": "USD", "marketplace": "Online_US", "score": 18.205433, "p_click": 0.0, "p_order": 0.0, "goal": 2, "category_id": 113, "subcategory_id": 13999, "format": null, "is_paid": false, "online_event": true, "event_start_date": "2024-06-28T00:00:00Z", "latitude": null, "longitude": null, "name": "\"Girl Let's Talk\" Virtual 90s Kickback", "vip_status": false, "is_participant": true}]}
Как заметил один комментатор, я думаю, что я ищу регулярное выражение, которое будет соответствовать шаблону и удалять его \", но у меня его не было удачи с этим пока! Мне удалось удалить только \s, в результате чего у меня остались двойные кавычки, которые нарушают json.loads() (ожидая разделителя, который думает, что это еще одна пара ключ/значение JSON), или удалить все двойные кавычки, что, конечно, полностью нарушает то же самое.
РЕДАКТИРОВАНИЕ ПОСЛЕ РЕШЕНИЯ: Вот воспроизводимый пример ошибки и ее исправления:
Код: Выделить всё
import json
json_string = '''{"name": "John",
"description": "I'm just \"A BOY\" okay? He said \"Hello, World!\" to everyone.",
"remark": "\"This is a test\" he mentioned."}'''
data = json.loads(json_string)
print(data)
Код: Выделить всё
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 27 (char 43)Код: Выделить всё
import json
json_string = r'''{"name": "John",
"description": "I'm just \"A BOY\" okay? He said \"Hello, World!\" to everyone.",
"remark": "\"This is a test\" he mentioned."}'''
data = json.loads(json_string)
print(data)
Код: Выделить всё
{'name': 'John', 'description': 'I\'m just "A BOY" okay? He said "Hello, World!" to everyone.', 'remark': '"This is a test" he mentioned.'}Подробнее здесь: https://stackoverflow.com/questions/786 ... -to-remove