Одинарные и двойные кавычки в JSON
мой код:
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
#1 определение неверно
#2 определение права
Я слышал, что в Python эта одиночная двойная цитата может быть взаимозаменяемой, может ли кто-нибудь объяснить это для меня?
7 ответов:
синтаксис JSON не синтаксис Python. JSON требует двойных кавычек для своих строк.
можно использовать
ast.literal_eval()>>> import ast >>> s = "{'username':'dfdsfdsf'}" >>> ast.literal_eval(s) {'username': 'dfdsfdsf'}
вы можете сбросить JSON с двойной кавычкой:
from json import dumps #mixing single and double quotes data = {'jsonKey': 'jsonValue',"title": "hello world"} jsonString = json.dumps(data) #get string with all double quotes
demjson также является хорошим пакетом для решения проблемы плохого синтаксиса json:
pip install demjsonиспользование:
from demjson import decode bad_json = "{'username':'dfdsfdsf'}" python_dict = decode(bad_json)Edit:
demjson.decodeэто отличный инструмент для поврежденных json, но когда вы имеете дело с большой amourt данных jsonast.literal_evalЭто лучший матч и гораздо быстрее.
Как уже было сказано, JSON не является синтаксисом Python. Вам нужно использовать двойные кавычки в JSON. Его создатель (in-)известен использованием строгих подмножеств допустимого синтаксиса для облегчения когнитивной перегрузки программиста.
Это очень полезным чтобы знать, что в строке JSON нет одинарных кавычек. Допустим, вы скопировали и вставили его из консоли браузера/все. Затем, вы можете просто ввести
a = json.loads('very_long_json_string_pasted_here')в противном случае это может сломаться, если он также использовал одинарные кавычки.
недавно я столкнулся с очень похожей проблемой, и считаю мое решение будет работать для вас тоже. У меня был текстовый файл, который содержал список элементов в виде:
["first item", 'the "Second" item', "thi'rd", 'some \"hellish\" \'quoted" item']Я хотел разобрать выше в список python, но не был увлечен eval (), поскольку я не мог доверять входным данным. Я попробовал сначала использовать JSON, но он принимает только двойные кавычки, поэтому я написал свой собственный очень простой лексер для этого конкретного случая (просто подключите свой собственный "stringtoparse", и вы получите результат список: 'предметы')
#This lexer takes a JSON-like 'array' string and converts single-quoted array items into escaped double-quoted items, #then puts the 'array' into a python list #Issues such as ["item 1", '","item 2 including those double quotes":"', "item 3"] are resolved with this lexer items = [] #List of lexed items item = "" #Current item container dq = True #Double-quotes active (False->single quotes active) bs = 0 #backslash counter in_item = False #True if currently lexing an item within the quotes (False if outside the quotes; ie comma and whitespace) for c in stringtoparse[1:-1]: #Assuming encasement by brackets if c=="\": #if there are backslashes, count them! Odd numbers escape the quotes... bs = bs + 1 continue if (dq and c=='"') or (not dq and c=="'"): #quote matched at start/end of an item if bs & 1==1: #if escaped quote, ignore as it must be part of the item continue else: #not escaped quote - toggle in_item in_item = not in_item if item!="": #if item not empty, we must be at the end items += [item] #so add it to the list of items item = "" #and reset for the next item continue if not in_item: #toggle of single/double quotes to enclose items if dq and c=="'": dq = False in_item = True elif not dq and c=='"': dq = True in_item = True continue if in_item: #character is part of an item, append it to the item if not dq and c=='"': #if we are using single quotes item += bs * "\" + "\"" #escape double quotes for JSON else: item += bs * "\" + c bs = 0 continueнадеюсь, это кому-нибудь пригодится. Наслаждайтесь!
Comments