0

Sorry for the duplicate title type. I am having a problem finding and example on how to accomplish this. I have a json file I'm pulling from Zendesk. I'm doing a json.dumps to get that to a readable formation and in a python dictionary. I have the following in a for loop so I can get just the info I need out of the json file and write it to a csv file.

for item in data['results']:
    print(
        item['id'] ,item['via']['channel'], item['via']['source']['from'], item['subject'], item['tags'],
        item['created_at'], item['status'], item['custom_fields'][12], item['custom_fields'][12]['value'],
        item['result_type'], item['priority']

from this code I get the items I want with the correct information.

I have tried the following to print this out to a file but all I get returned in the file is the last record

import csv

with open('file.txt', 'w') as file:

csv_app = csv.writer(file)
for item in python_data['results']:
    csv_app.writerows(item['id'], item['via']['channel'],item['via']['source']['from'],item['subject'], item['tags'],
           item['created_at'], item['status'], item['custom_fields'][12], item['custom_fields'][12]['value'],
           item['priority'], item['result_type'])

I would like to get some suggestions on how to get everything (i've tried alot of stuff) Also there is an item['via']['source']['from']['name'] I have taken out due to it causing errors when there is no value there. How do I handle this on a field by field basis I'm assuming a if condition.

Any help or pointing me in the right direction would be greatly appreciated.

Thanks in advance.

Sc-python-leaner
  • 259
  • 1
  • 2
  • 13

1 Answers1

0

First, file is a reserved word in python. Use something else such as f or fout.

Second, use writerow instead of writerows.

Third, your indentation is off in your example (last five lines should be indented one level).

import csv

data = {'results': [{'A': 1, 'B': 2, 'C': 3}, 
                    {'A': 10, 'B': 20, 'C': 30}]}
with open('test.txt', 'w') as f:
    csv_app = csv.writer(f)
    for item in data['results']:
        csv_app.writerow([item[x] for x in ['A', 'B', 'C']])

$ cat test.txt
1,2,3
10,20,30
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • Perfect that you Alexander, I swear I have tried this same thing but the last line was the key, I'm able to get what I need out now. Really appreciate the help. – Sc-python-leaner Nov 28 '17 at 18:48
  • Well almost worked, I have a description field that can get quite large and don't know what's causing it but getting a unicodeEncodeError 'charmap' codec can't encode character '\u2502' in position 799: character maps to – Sc-python-leaner Nov 28 '17 at 19:11
  • Perhaps this will help: https://stackoverflow.com/questions/27092833/unicodeencodeerror-charmap-codec-cant-encode-characters – Alexander Nov 28 '17 at 19:17