Lab Exercise 12 - Read JSON Using PyQt
Lab Exercise 12 - Read JSON Using PyQt
Lab Exercise: Read JSON file with PyQt and QML and Present on QTable
Creating a PyQt project to read and display JSON data involves several steps. In this
example, I'll provide a simple PyQt application that loads JSON data from a file and
displays it in a table widget. You'll need to have PyQt5 installed. If you haven't
already installed it, you can use pip to install it:
Test.json
{
"name": "John Doe",
"age": 30,
"city": "New York",
"email": "[email protected]",
"hobbies": ["Reading", "Hiking", "Cooking"],
"is_student": false
}
Now, you can create a PyQt application to read and display JSON data. Here's a basic
example:
import sys
import json
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget,
QTableWidgetItem, QVBoxLayout, QPushButton, QWidget, QFileDialog
class JSONViewer(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('JSON Viewer')
central_layout.addWidget(self.load_button)
central_widget.setLayout(central_layout)
def load_json(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "Open JSON File", "", "JSON
Files (*.json);;All Files (*)", options=options)
if file_name:
with open(file_name, 'r') as json_file:
data = json.load(json_file)
def main():
app = QApplication(sys.argv)
ex = JSONViewer()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Save this code in a Python file (e.g., json_viewer.py) and run it. This PyQt application
provides a simple user interface with a "Load JSON" button. When you click the
button, you can select a JSON file, and the application will display the JSON data in a
table format.