1import json
2
3# some JSON:
4x = '{ "name":"John", "age":30, "city":"New York"}'
5
6# parse x:
7y = json.loads(x)
8
9# the result is a Python dictionary:
10print(y["age"])
11
1# a Python object (dict):
2x = {
3 "name": "John",
4 "age": 30,
5 "city": "New York"
6}
7
8# convert into JSON:
9y = json.dumps(x)
1#load and print elements of a json file
2import json
3file = "my_json_file.json"
4
5Json = json.load(open(file)) #Json is a dictionary
6
7print(Json)
8#OUTPUT: '{ "name":"John", "age":30, "city":"New York"}'
9
10print("Hello",Json["name"])
11#OUTPUT: Hello John
1import json
2
3# The json itself.
4x = {
5 "name": "Jeff",
6 "age": "22",
7 "cars": [
8 {"model": "BMW 230", "mpg": 27.5},
9 {"model": "Ford Egde", "mpg": 27.5}
10 ]
11}
12
13if x["cars"] != None: # Checking if cars is not None
14 car = x["name"]+ " has " + str(len(x["cars"])) + " cars: " # May be changed
15 for i in range(0, len(x["cars"])):
16 car += "Car "+ str(i+1) + ": " + x["cars"][i]["model"] + " that has a MPG of " + str(x["cars"][i]["mpg"]) + ", "
17 car = car[0:-2] + "."
18 print(car)
19else:
20 print(x["name"] + " does not have any cars!")
1>>> import json
2>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
3['foo', {'bar': ['baz', None, 1.0, 2]}]
4>>> json.loads('"\\"foo\\bar"')
5'"foo\x08ar'
6>>> from io import StringIO
7>>> io = StringIO('["streaming API"]')
8>>> json.load(io)
9['streaming API']
1>>> import json
2>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
3['foo', {'bar': ['baz', None, 1.0, 2]}]
4>>> json.loads('"\\"foo\\bar"')
5'"foo\x08ar'
6>>> from io import StringIO
7>>> io = StringIO('["streaming API"]')
8>>> json.load(io)
9['streaming API']
10