Python JSON 中的单引号和双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4162642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single vs double quotes in JSON
提问by Bin Chen
My code:
我的代码:
import simplejson as json
s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)
#1definition is wrong
#1定义错误
#2definition is right
#2定义是对的
I heard that in Python that singleand doublequote can be interchangable. Can anyone explain this to me?
我听说在 Python 中单引号和双引号可以互换。任何人都可以向我解释这一点吗?
采纳答案by Ignacio Vazquez-Abrams
JSON syntaxis not Python syntax. JSON requires double quotes for its strings.
JSON 语法不是 Python 语法。JSON 的字符串需要双引号。
回答by cowboybkit
You can dump JSON with double quote by:
您可以通过以下方式使用双引号转储 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)
回答by hahakubile
you can use ast.literal_eval()
您可以使用 ast.literal_eval()
>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}
回答by DhiaTN
demjsonis also a good package to solve the problem of bad json syntax:
demjson也是一个很好的包,可以解决 json 语法不好的问题:
pip install demjson
Usage:
用法:
from demjson import decode
bad_json = "{'username':'dfdsfdsf'}"
python_dict = decode(bad_json)
Edit:
编辑:
demjson.decodeis a great tool for damaged json, but when you are dealing with big amourt of json dataast.literal_evalis a better match and much faster.
demjson.decode对于损坏的 json 来说是一个很好的工具,但是当你处理大量的 json 数据时,它ast.literal_eval是一个更好的匹配,而且速度更快。
回答by Dheeraj R
import json
data = json.dumps(list)
print(data)
The above code snippet should work.
上面的代码片段应该可以工作。
回答by serv-inc
As said, JSON is not Python syntax. You need to use double quotes in JSON. Its creator is (in-)famous for using strict subsets of allowable syntax to ease programmer cognitive overload.
如前所述,JSON 不是 Python 语法。您需要在 JSON 中使用双引号。它的创建者因使用允许语法的严格子集来减轻程序员的认知负担而闻名(in-)。
Below can fail if one of the JSON strings itself contains a single quote as pointed out by @Jiaaro. DO NOT USE. Left here as an example of what does not work.
如果 JSON 字符串之一本身包含@Jiaaro 指出的单引号,则下面可能会失败。不使用。留在这里作为什么不起作用的例子。
It is really usefulto know that there are no single quotes in a JSON string. Say, you copied and pasted it from a browser console/whatever. Then, you can just type
这是非常有用的知道有一个JSON字符串没有单引号。说,你从浏览器控制台/任何地方复制并粘贴了它。然后,您只需键入
a = json.loads('very_long_json_string_pasted_here')
This might otherwise break if it used single quotes, too.
如果它也使用单引号,这可能会中断。
回答by Matt
I recently came up against a very similar problem, and believe my solution would work for you too. I had a text file which contained a list of items in the form:
我最近遇到了一个非常相似的问题,相信我的解决方案也适用于你。我有一个文本文件,其中包含以下形式的项目列表:
["first item", 'the "Second" item', "thi'rd", 'some \"hellish\" \'quoted" item']
I wanted to parse the above into a python list but was not keen on eval() as I couldn't trust the input. I tried first using JSON but it only accepts double quoted items, so I wrote my own very simple lexer for this specific case (just plug in your own "stringtoparse" and you will get as output list: 'items')
我想将上述内容解析为一个 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
Hopefully it is useful to somebody. Enjoy!
希望它对某人有用。享受!
回答by vaibhav.patil
import ast
answer = subprocess.check_output(PYTHON_ + command, shell=True).strip()
print(ast.literal_eval(answer.decode(UTF_)))
Works for me
为我工作
回答by Robin Ali
You can fix it that way:
你可以这样修复它:
s = "{'username':'dfdsfdsf'}"
j = eval(s)
回答by Hafiz Hashim
It truly solved my problem using eval function.
它使用 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)

