Python:从JSON转储中删除双引号 [英] Python: remove double quotes from JSON dumps
问题描述
我有一个数据库,该数据库以以下格式将行作为列表返回:
I have a database which returns the rows as lists in following format:
data = ['(1000,"test value",0,0.00,0,0)', '(1001,"Another test value",0,0.00,0,0)']
之后,我使用json_str = json.dumps(data)
来获取JSON字符串.应用json.dumps()
之后,我得到以下输出:
After that, I use json_str = json.dumps(data)
to get a JSON string. After applying json.dumps()
, I get the following output:
json_str = ["(1000,\"test value\",0,0.00,0,0)", "(1001,\"Another test value\",0,0.00,0,0)"]
但是,我需要以下格式的JSON字符串:
However, I need the JSON string in the following format:
json_str = [(1000,\"test value\",0,0.00,0,0), (1001,\"Another test value\",0,0.00,0,0)]
所以基本上,我想删除周围的双引号.我尝试使用json_str = json_str.strip('"')
完成此操作,但这不起作用.然后,我尝试了json_str = json_str.replace('"', '')
,但这也删除了转义的引号.
So basically, I want to remove the surrounding double quotes. I tried to accomplish this with json_str = json_str.strip('"')
but this doesn't work. Then, I tried json_str = json_str.replace('"', '')
but this also removes the escaped quotes.
有人知道实现此目的的方法吗?还是Python中有类似json.dumps()
的函数产生相同的结果,但周围没有双引号?
Does anybody know a way to accomplish this or is there a function in Python similiar to json.dumps()
which produces the same result, but without the surrounding double quotes?
推荐答案
您正在转储字符串列表,因此json.dumps完全符合您的要求.对于您的问题而言,丑陋的解决方案可能如下所示.
You are dumping list of strings so json.dumps does exactly what you are asking for. Rather ugly solution for your problem could be something like below.
def split_and_convert(s):
bits = s[1:-1].split(',')
return (
int(bits[0]), bits[1], float(bits[2]),
float(bits[3]), float(bits[4]), float(bits[5])
)
data_to_dump = [split_and_convert(s) for s in data]
json.dumps(data_to_dump)
这篇关于Python:从JSON转储中删除双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!