5

Im retrieving a report from the google adwords api as string which contains csv (using downloadReportAsString). I want to convert this to JSON, only all the converters expect a csv file type but mine is currently a string. How do I get the string to csv file? I read something about stringIO. I'm using python 3

1
  • Unclear what format of JSON you want. Please give example Commented Jun 9, 2017 at 16:25

1 Answer 1

13

By using io.StringIO you can use the normal csv readers and then dump it out to json.

>>> import csv, io, json
>>> 
>>> string = """a,b,c
... 1,2,3
... 4,5,6
... """
>>> 
>>> reader = csv.DictReader(io.StringIO(string))
>>> 
>>> json_data = json.dumps(list(reader))
>>> json_data
'[{"a": "1", "b": "2", "c": "3"}, {"a": "4", "b": "5", "c": "6"}]'
Sign up to request clarification or add additional context in comments.

3 Comments

I actually didn't take it right from there. I guess abc123 is common test data. Thanks for linking though! That answer also has a bit better explanation.
json_data is a string. How can be obtained as a Python dictionary?

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.