Created
August 26, 2015 02:26
-
-
Save tonywhittaker/93fc9768fa135149edd3 to your computer and use it in GitHub Desktop.
CSV to JSON with Flask & Bootstrap
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>CSV to JSON</title> | |
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<div class="col-sm-8 col-sm-offset-2"> | |
<legend> | |
<h3>CSV to JSON<br> | |
<small>Files must be csv.</small></h3></legend> | |
<form align="center" action="/csv2json" method="post" enctype="multipart/form-data" class="form-horizontal"> | |
<fieldset> | |
<div class="form-group"> | |
<label class="col-sm-2 control-label">File</label> | |
<div class="col-sm-5"> | |
<input type="file" name="data_file" placeholder="file" class="form-control" required="true"> | |
</div> | |
</div> | |
<div class="form-group"> | |
<div class="col-sm-5 col-sm-offset-2"> | |
<input type="submit" class="btn btn-primary form-control" /> | |
</div> | |
</div> | |
</fieldset> | |
</div> | |
</form> | |
</body> | |
</html> |
This file contains hidden or 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 csv | |
import json | |
from cStringIO import StringIO | |
from flask import Flask, render_template, request, make_response | |
app = Flask(__name__) | |
app.debug = True | |
def csv2json(data): | |
reader = csv.DictReader | |
reader = csv.DictReader(data) | |
out = json.dumps([ row for row in reader ]) | |
print "JSON parsed!" | |
return out | |
print "JSON saved!" | |
@app.route('/csv2json', methods=["POST"]) | |
def convert(): | |
f = request.files['data_file'] | |
if not f: | |
return "No file" | |
file_contents = StringIO(f.stream.read()) | |
result = csv2json(file_contents) | |
response = make_response(result) | |
response.headers["Content-Disposition"] = "attachment; filename=Converted.json" | |
return response | |
@app.route('/') | |
def main(): | |
render_template | |
return render_template('convert.html') | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment