import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary (object):
print(y["age"])
# a Python dictionary (object):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
# Loop + JSON:
customersJSON = """
[
{ "name":"Alice", "age":20, "city":"London"},
{ "name":"Eve", "age":22, "city":"Berlin"},
{ "name":"Aria", "age":33, "city":"Vienna"},
{ "name":"Frank", "age":27, "city":"Madrid"},
{ "name":"Grace", "age":32, "city":"Rome"},
{ "name":"Henry", "age":29, "city":"Amsterdam"},
{ "name":"Isabella", "age":24, "city":"Vienna"}
]
"""
customers = json.loads(customersJSON)
totalAge = 0
nrOfPersons = 0
for customer in customers:
totalAge += customer['age']
nrOfPersons += 1
avgAge = totalAge / nrOfPersons
print(F'The average age of all {nrOfPersons} customers is: {avgAge}')