more JavaScript Object Notation (JSON) examples
JavaScript Object Notation (JSON) is syntax for (the actual) text that is written to store and exchange data, which can be used by any programming language. JSON is shorter and quicker to write than XML, and far easier to use.
simpleJSONexample.py
#simple JSON demonstration import json #1. create a python dictionary: applicant = { "name": "Proudlock", "age": 40, "driverslicense": False, "qualifications": ("Degree","Diploma"), "experience": [ {"Maccas": 2015}, {"KFC": 2019} ] } #2. convert to json: jsontext = json.dumps(applicant) print("JSON:", jsontext) #3. convert back to a python dictionary: pythondict = json.loads(jsontext) print("AGE:", pythondict["age"])
JSONserver.py
from flask import Flask from flask import jsonify app = Flask(__name__) applicant = { "name": "Proudlock", "age": 40, "driverslicense": False, "qualifications": ("Degree","Diploma"), "experience": [ {"Maccas": 2015}, {"KFC": 2019} ] } @app.route("/summary") def getdata(): return jsonify(applicant) app.run()
JSONrequest.py
import requests import json answer = requests.get("http://127.0.0.1:5000/summary") print(answer.headers['content-type']) #application/json print(answer.text) #actual JSON string #convert to Python dictionary: applicant = json.loads(answer.text) print("Age:", applicant["age"])