0

I am fetching data from a MySQL database and writing into a CSV file. This looks like this :

with open("output.csv", "ab+") as csv_file:
        csv_writer = csv.writer(csv_file)
        csv_writer.writerows(db_cursor)

This works fine with normal columns. However, I have a column which is of type LONGTEXT and has JSON data in it.

csv_writer adds extra quotes around each key value in the JSON when it creates the CSV file.

i.e., if my column has this value : {"key":"value"}

the output.csv file has : "{""key"" : ""value""}"

What I want is : "{\"key\" : \"value\"}"

How do I achieve this ?

(I have to read this file again in a ruby app and recreate the json. With this extra quotes, I am not sure how do I handle that!)

1 Answer 1

4

To specify how the output should be formatted, you need to pass the correct formatting parameters when creating the writer, or create you own dialect and use that.

In your case, you'll probably want something like this:

csv_writer = csv.writer(csv_file,
                        doublequote=False,
                        escapechar='\\',
                        quoting=csv.QUOTE_NONNUMERIC)

This uses the default (excel) dialect while overriding the supplied parameters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.