Created
October 30, 2015 16:08
-
-
Save reinaldons/098c8ed42ebeaf2a339b to your computer and use it in GitHub Desktop.
Load a JSON generated by SMS-GW API /api/v1/products/(product_name)/messages and wwriting a CSV file with some fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import csv | |
from optparse import OptionParser | |
def json_to_csv(json_filename, csv_filename): | |
with open(json_filename, 'r') as json_file: | |
json_decoded = json.load(json_file) | |
with open(csv_filename, 'w') as csv_file: | |
spamwriter = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) | |
spamwriter.writerow(['msisdn', 'message_type', 'message_uuid', 'content', 'carrier_name', | |
'backend_name', 'product_name', 'created_dt', 'status']) | |
for message in json_decoded['messages']: | |
spamwriter.writerow([message['msisdn'], message['message_type'], message['message_uuid'], | |
message['content'], message['carrier_name'], message['backend_name'], | |
message['product_name'], message['created_dt'], message['status']]) | |
if __name__ == '__main__': | |
parser = OptionParser() | |
parser.add_option("-j", "--json", dest="json_filename", help="JSON file", metavar="FILE") | |
parser.add_option("-c", "--csv", dest="csv_filename", help="CSV file", metavar="FILE") | |
(options, args) = parser.parse_args() | |
json_to_csv(json_filename=options.json_filename, csv_filename=options.csv_filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment