Tag: JSON
JSON encoding and decoding with Python
Introduction
JSON (JavaScript Object Notation) is frequently used between a server and a web application. An example of JSON data:
{ "persons": [ { "city": "Seattle", "name": "Brian" }, { "city": "Amsterdam", "name": "David" } ] } |
The json module enables you to convert between JSON and Python Objects.
JSON conversion examples
Convert JSON to Python Object (Dict)
To convert JSON to a Python dict use this:
import json json_data = '{"name": "Brian", "city": "Seattle"}' python_obj = json.loads(json_data) print python_obj["name"] print python_obj["city"] |
Convert JSON to Python Object (List)
JSON data can be directly mapped to a Python list.
import json array = '{"drinks": ["coffee", "tea", "water"]}' data = json.loads(array) for element in data['drinks']: print element |
Convert JSON to Python Object (float)
Floating points can be mapped using the decimal library.
import json from decimal import Decimal jsondata = '{"number": 1.573937639}' x = json.loads(jsondata, parse_float=Decimal) print x['number'] |
Convert JSON to Python Object (Example)
JSON data often holds multiple objects, an example of how to use that below:
import json json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }' try: decoded = json.loads(json_input) # Access data for x in decoded['persons']: print x['name'] except (ValueError, KeyError, TypeError): print "JSON format error" |
Convert Python Object (Dict) to JSON
If you want to convert a Python Object to JSON use the json.dumps() method.
import json from decimal import Decimal d = {} d["Name"] = "Luke" d["Country"] = "Canada" print json.dumps(d, ensure_ascii=False) # result {"Country": "Canada", "Name": "Luke"} |
Converting JSON data to Python objects
JSON data can be converted (deserialized) to Pyhon objects using the json.loads() function. A table of the mapping:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Pretty printing
If you want to display JSON data you can use the json.dumps() function.
import json json_data = '{"name": "Brian", "city": "Seattle"}' python_obj = json.loads(json_data) print json.dumps(python_obj, sort_keys=True, indent=4) |
Flask, JSON and the Google Charts API
This tutorial will teach you how to build a Flask app that combined with JSON and the Google Charts API. If you have no experience with Flask before I recommend reading my previous tutorials, they are great fun!
Related course
Python Flask: Make Web Apps with Python
$ pip install Flask |
Create a file called hello.py
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() |
Finally run the web app using this command:
$ python hello.py * Running on http://localhost:5000/ |
Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.
Get JSON data
To display awesome charts we first need some data. There are two common ways to get data in web apps: data from servers using an API (usually JSON) and data from databases. I use the Fixer.io JSON API to get some financial data, but any JSON API should do. If you are unfamiliar with JSON, see this article.
We wrote this script to get the exchange rates:
import json import urllib2 def getExchangeRates(): rates = [] response = urllib2.urlopen('http://api.fixer.io/latest') data = response.read() rdata = json.loads(data, parse_float=float) rates.append( rdata['rates']['USD'] ) rates.append( rdata['rates']['GBP'] ) rates.append( rdata['rates']['JPY'] ) rates.append( rdata['rates']['AUD'] ) return rates rates = getExchangeRates() print rates |
Google Charts API with Flask
With the Google Charts API you can display live data on your site. There are a lot of great charts there that are easy to add to your Flask app. We simply give the data that we got from the server through JSON and parsed, to the Google Charts API.
Create a flask app with the directory /templates/ for your templates. This is the main Flask code:
from flask import Flask, flash, redirect, render_template, request, session, abort import os import json import urllib2 tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) def getExchangeRates(): rates = [] response = urllib2.urlopen('http://api.fixer.io/latest') data = response.read() rdata = json.loads(data, parse_float=float) rates.append( rdata['rates']['USD'] ) rates.append( rdata['rates']['GBP'] ) rates.append( rdata['rates']['HKD'] ) rates.append( rdata['rates']['AUD'] ) return rates @app.route("/") def index(): rates = getExchangeRates() return render_template('test.html',**locals()) @app.route("/hello") def hello(): return "Hello World!" if __name__ == "__main__": app.run() |
And we have this template:
{% block body %} <script type="text/javascript" src="https://www.google.com/jsapi"></script> <div id="chart_div" style="width: 900px; height: 300px;"> <div> <script type="text/javascript">//<![CDATA[ google.load('visualization', '1', {packages: ['corechart', 'bar']});<br /> google.setOnLoadCallback(drawBasic);</p> <p>function drawBasic() {</p> <p> var data = google.visualization.arrayToDataTable([<br /> ['Currency', 'Rate', { role: 'style' }],<br /> ['USD', {{rates[0]}}, 'gold'],<br /> ['GBP', {{rates[1]}}, 'silver'],<br /> ['HKD', {{rates[2]}}, 'brown'],<br /> ['AUD', {{rates[3]}}, 'blue']<br /> ]);</p> <p> var options = {<br /> title: 'Exchange rate overview',<br /> chartArea: {width: '50%'},<br /> hAxis: {<br /> title: '',<br /> minValue: 0<br /> },<br /> vAxis: {<br /> title: ''<br /> }<br /> };</p> <p> var chart = new google.visualization.BarChart(document.getElementById('chart_div'));</p> <p> chart.draw(data, options);<br /> }<br /> //]]> </p> <p></script> {% endblock %} |
Result:
