5

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 = ["(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_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.

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2494129
  • 717
  • 2
  • 13
  • 24
  • Just dump that all that as dictionary rather than string. https://stackoverflow.com/questions/25242262/dump-to-json-adds-additional-double-quotes-and-escaping-of-quotes – Sushant Rathod May 23 '20 at 18:11
  • Just dump the data as a dictionary rather than string value [enter link description here](https://stackoverflow.com/questions/25242262/dump-to-json-adds-additional-double-quotes-and-escaping-of-quotes) – Sushant Rathod May 23 '20 at 18:12

1 Answers1

2

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)
zero323
  • 322,348
  • 103
  • 959
  • 935