import json
path="D:\\my_data\\student.json" # Json file path
f=open(path,'r') # open in read mode
data=json.load(f) # data collected
for row in data:
print(row)
import json
from urllib.request import urlopen
url = "https://www.plus2net.com/php_tutorial/student.json" # Json file path
f = urlopen(url) # Open the URL
data = json.load(f) # Data collected
for row in data:
print(row)
Output
{
'id': 1,
'name': 'John Deo',
'class': 'Four',
'mark': 75,
'gender': 'female'
}
{
'id': 2,
'name': 'Max Ruin',
'class': 'Three',
'mark': 85,
'gender': 'male'
}
{
'id': 3,
'name': 'Arnold',
'class': 'Three',
'mark': 55,
'gender': 'male'
}
{
'id': 4,
'name': 'Krish Star',
'class': 'Four',
'mark': 60,
'gender': 'female'
}
----
---
Here are some common methods used for managing Json strings.
| Python | Json |
|---|---|
| Dictionary | Object |
| list, Tuple | Array |
| String , Unicode | String |
| int, long, float | Number |
| True | true |
| False | false |
| None | null |
| Json | Python |
|---|---|
| Object | Dictionary |
| Array | List |
| string | Unicode |
| Number (int ) | int , long |
| Number ( real ) | float |
| true | True |
| false | False |
| null | None |
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://userid:password@localhost/my_database")
my_connect = engine.connect()
import json
rs = my_connect.execute("SELECT * FROM student WHERE class='Three'")
my_data = rs.fetchall() # A list
j = json.dumps([dict(r) for r in my_data])
print(j)
my_connect.close()
Output
[{"id": 2, "name": "Max Ruin", "class": "Three", "mark": 85, "sex": "male"},
{"id": 3, "name": "Arnold", "class": "Three", "mark": 55, "sex": "male"},
{"id": 27, "name": "Big Nose", "class": "Three", "mark": 81, "sex": "female"}]
import json
path = "D:\\my_data\\student.json" # Use your sample file
fob = open(path,)
data = json.load(fob)
names = []
for student in data:
# print(student['name'])
names.append(student['name'])
print(names)
fob.close()
Using list comprehension, we can create the same list in one statement.
names=[r['name'] for r in data]
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.