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
Asked
Active
Viewed 8,909 times
5
-
Unclear what format of JSON you want. Please give example – OneCricketeer Jun 09 '17 at 16:25
1 Answers
11
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"}]'

Brobin
- 3,241
- 2
- 19
- 35
-
1I 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. – Brobin Jun 09 '17 at 16:26
-
Also: [CSV to JSON](https://stackoverflow.com/questions/19697846/python-csv-to-json) – OneCricketeer Jun 09 '17 at 16:27
-
json_data is a string. How can be obtained as a Python dictionary? – eduardosufan Jun 23 '22 at 18:00