Python Lesson 16
Python Lesson 16
• JSON in Python
• Parse JSON - Convert from JSON to Python
• Convert from Python to JSON
• Format the Result
• Order the Result
• Python - JSON Exercises
Python Math
Python has a set of built-in math functions, including an extensive math module, that allows you to
perform mathematical tasks on numbers.
The abs() function returns the absolute (positive) value of the specified number:
Example
x = abs(-7.25)
print(x)
The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method
rounds a number downwards to its nearest integer, and returns the result:
Example
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
Example
Import the json module:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
Example
Convert Python objects into JSON strings, and print the values:
import json
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript)
equivalent:
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Example
Convert a Python object containing all the legal data types:
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
You can also define the separators, default value is (", ", ": "), which means using a comma and a space
to separate each object, and a colon and a space to separate keys from values:
Example
Use the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))