Python:从JSON转储中删除双引号

时间:2021-09-20 19:12:13

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)']

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 = JSON .dumps(data)来获得JSON字符串。应用json.dumps()之后,我得到以下输出:

json_str = ["(1000,\"test value\",0,0.00,0,0)", "(1001,\"Another test value\",0,0.00,0,0)"]

However, I need the JSON string in the following format:

但是,我需要以下格式的JSON字符串:

json_str = [(1000,\"test value\",0,0.00,0,0), (1001,\"Another test value\",0,0.00,0,0)]

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.

基本上,我想去掉周围的双引号。我尝试用json_str = json_str.strip(' ')来完成它,但这不起作用。然后,我尝试了json_str = json_str。替换(' ''),但这也删除了转义引号。

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?

有人知道实现这个目标的方法吗?或者Python中是否有一个与json.dumps()类似的函数,它会产生相同的结果,但是没有周围的双引号?

1 个解决方案

#1


1  

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.

将字符串列表转储为json。转储完全符合您的要求。对于你的问题,很难看的解决方案可能是下面这样的。

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)

#1


1  

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.

将字符串列表转储为json。转储完全符合您的要求。对于你的问题,很难看的解决方案可能是下面这样的。

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)