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

1oneSquared
  • 113
  • 2
  • 7

1 Answers1

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