[英]Single vs double quotes in JSON
我的代碼:
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
#1
定義錯誤
#2
定義正確
我聽說在 Python 中單引號和雙引號可以互換。 任何人都可以向我解釋這一點嗎?
JSON 語法不是 Python 語法。 JSON 的字符串需要雙引號。
你可以使用ast.literal_eval()
>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}
您可以通過以下方式使用雙引號轉儲 JSON:
import json
# mixing single and double quotes
data = {'jsonKey': 'jsonValue',"title": "hello world"}
# get string with all double quotes
json_string = json.dumps(data)
demjson也是一個很好的包,可以解決 json 語法不好的問題:
pip install demjson
用法:
from demjson import decode
bad_json = "{'username':'dfdsfdsf'}"
python_dict = decode(bad_json)
編輯:
demjson.decode
對於損壞的 jsondemjson.decode
是一個很好的工具,但是當你處理大量的 json 數據時,ast.literal_eval
是一個更好的匹配,而且速度更快。
到目前為止給出的答案有兩個問題,例如,如果一個流傳輸這樣的非標准 JSON。 因為那時可能必須解釋傳入的字符串(而不是 python 字典)。
問題 1 - demjson
:使用 Python 3.7.+ 並使用 conda 我無法安裝 demjson,因為它目前不支持 Python > 3.5。 所以我需要一個更簡單的解決方案,例如ast
和/或json.dumps
。
問題 2 - ast
和json.dumps
:如果 JSON 是單引號並且包含至少一個值中的字符串,而該字符串又包含單引號,我發現的唯一簡單而實用的解決方案是同時應用兩者:
在以下示例中,我們假設line
是傳入的 JSON 字符串對象:
>>> line = str({'abc':'008565','name':'xyz','description':'can control TV\'s and more'})
第 1 步:使用ast.literal_eval()
將傳入的字符串轉換為字典
第 2 步:將json.dumps
應用於它以實現鍵和值的可靠轉換,但不涉及值的內容:
>>> import ast
>>> import json
>>> print(json.dumps(ast.literal_eval(line)))
{"abc": "008565", "name": "xyz", "description": "can control TV's and more"}
單獨的json.dumps
不會完成這項工作,因為它不會解釋 JSON,而只會看到字符串。 與ast.literal_eval()
類似:雖然它正確解釋了 JSON(字典),但它不會轉換我們需要的內容。
你可以這樣修復它:
s = "{'username':'dfdsfdsf'}"
j = eval(s)
如前所述,JSON 不是 Python 語法。 您需要在 JSON 中使用雙引號。 它的創建者因使用允許語法的嚴格子集來減輕程序員的認知負擔而聞名(in-)。
如果 JSON 字符串之一本身包含@Jiaaro 指出的單引號,則下面可能會失敗。 不使用。 留在這里作為什么不起作用的例子。
知道 JSON 字符串中沒有單引號非常有用。 說,你從瀏覽器控制台/任何地方復制並粘貼了它。 然后,您只需鍵入
a = json.loads('very_long_json_string_pasted_here')
如果它也使用單引號,這可能會中斷。
它使用 eval 函數真正解決了我的問題。
single_quoted_dict_in_string = "{'key':'value', 'key2': 'value2'}"
desired_double_quoted_dict = eval(single_quoted_dict_in_string)
# Go ahead, now you can convert it into json easily
print(desired_double_quoted_dict)
我最近遇到了一個非常相似的問題,相信我的解決方案也適用於你。 我有一個文本文件,其中包含以下形式的項目列表:
["first item", 'the "Second" item', "thi'rd", 'some \\"hellish\\" \'quoted" item']
我想將上面的內容解析成一個 python 列表,但對 eval() 不感興趣,因為我不能相信輸入。 我首先嘗試使用 JSON,但它只接受雙引號項,所以我為這個特定情況編寫了我自己的非常簡單的詞法分析器(只需插入你自己的“stringtoparse”,你就會得到輸出列表:'items')
#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
希望它對某人有用。 享受!
您可以使用
json.dumps(your_json, separators=(",", ":"))
import ast
answer = subprocess.check_output(PYTHON_ + command, shell=True).strip()
print(ast.literal_eval(answer.decode(UTF_)))
為我工作
import json
data = json.dumps(list)
print(data)
上面的代碼片段應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.