无法删除python添加的json字符串中的额外双引号
我有一个文件,其内容是
I have a file whose contents are
{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}
当我使用python读取文件时,我得到的字符串为
When I read the file using python, I get the string as
"{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}"
我希望从字符串的开头和结尾删除双引号.从 python docs ,我开始知道如果字符串中有单引号,python 会自己添加双引号以避免转义.
I want the double quotes to be removed from the beginning and end of the string. From python docs , I came to know that python adds double quotes by itself if there are single quotes in the string to avoid escaping.
如果存储的文件是 JSON,那么它们是无效的.JSON 格式不允许使用单引号来分隔字符串.假设您在键/值字符串中没有单引号,您可以将单引号替换为双引号,然后使用 JSON 模块读入:
If the files as stored are intended to be JSON then they are invalid. The JSON format doesn't allow the use of single quotes to delimit strings. Assuming you have no single quotes within the key/value strings themselves, you can replace the single quotes with double quotes and then read in using the JSON module:
import json
x = "{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}"
x = x.replace("'", '"')
j = json.loads(x)
print j
产量:
{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}
或者:
如果数据是 Python dict
的字符串表示,您可以使用 eval
读取它.使用 eval
是危险的(请参阅 Ned Batchelder 关于它).也就是说,如果您自己编写了该文件并且您确信它不包含恶意代码,则可以使用 eval
将字符串读取为 Python 源代码:
If the data is the string representation of a Python dict
, you can read it in with eval
. Using eval
is dangerous (see Ned Batchelder's thoughts on it). That said, if you wrote the file yourself and you are confident that it contains no malicious code, you can use eval
to read the string as Python source code:
x = "{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}"
eval(x, {'__builtins__': {}})
产量:
{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}
不要养成这个习惯!正确的方法是将数据以适当的序列化格式保存到文件中,然后使用像 json
模块这样的库从磁盘读取它.
Don't make a habit of this though! The right way to do this is to save the data to a file in a proper serialization format and then to read it from disk using a library like the json
module.