PyQt : data is not JSON serializable

雨燕双飞 提交于 2019-12-24 01:17:01

问题


I am new to PyQt GUI. I want to get the data of a QLineEdit text box, and for that I am using the text() method. I am getting the data, but the data type is a QString. I need to transmit this as json data to a server, and for that I am using the json.dumps() method - but I get an error.

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import pygame.camera
import pygame.image
import json

app = QApplication(sys.argv)

class stackedExample(QWidget):

   def __init__(self):
      super(stackedExample, self).__init__()
      self.current_module = 'GUI'
      print (self.current_module)

      self.takeFinger = False

      self.personaldata = None
      self.vehicledata = None

      self.leftlist = QListWidget ()
      self.leftlist.insertItem (0, 'Personal Info' )

      self.stack1 = QWidget()

      self.stack1UI()

      self.Stack = QStackedWidget (self)
      self.Stack.addWidget (self.stack1)

      hbox = QHBoxLayout(self)
      hbox.addWidget(self.leftlist)
      hbox.addWidget(self.Stack)

      self.setLayout(hbox)
      self.leftlist.currentRowChanged.connect(self.display)
      self.setGeometry(450, 120, 30,30)

      self.show()
      sys.exit(app.exec_())
      print "2"

   def stack1UI(self):
      layout = QFormLayout()
      self.s1 = QLabel("System ID")
      self.s1_val = QLineEdit()
      layout.addRow(self.s1,self.s1_val)
      self.s2 = QLabel("Driver Name")
      self.s2_val = QLineEdit()
      layout.addRow(self.s2,self.s2_val)
      self.s3 = QLabel("Aadhar ID")
      self.s3_val = QLineEdit()
      layout.addRow(self.s3,self.s3_val)

      self.s4 = QLabel("Driver Phone")
      self.s4_val = QLineEdit()
      layout.addRow(self.s4,self.s4_val)

      self.s5 = QLabel("Age")
      self.s5_val = QLineEdit()
      layout.addRow(self.s5,self.s5_val)

      sex = QHBoxLayout()
      sex.addWidget(QRadioButton("Male"))
      sex.addWidget(QRadioButton("Female"))
      layout.addRow(QLabel("Sex"),sex)
      self.b4 = QPushButton("&Save")
      self.b4.setDefault(True)
      self.b4.clicked.connect(self.personalData)
      layout.addWidget(self.b4)
      self.stack1.setLayout(layout)

   def personalData(self):
      print (self.s1_val.toPlainText())
      print type(self.s1_val.text())
      if (self.s1_val.text().isEmpty()):
         print "s1 is empty"
         #self.popup_window()
      if (self.s2_val.text().isEmpty()):
         print "s2 is empty"
      if (self.s3_val.text().isEmpty()):
         print "s3 is empty"
      if (self.s4_val.text().isEmpty()):
         print "s4 is empty"
      if (self.s5_val.text().isEmpty()):
         print "s5 is empty"

      if(not self.s1_val.text().isEmpty() and not self.s2_val.text().isEmpty()):
         #Data1 = {'systemID':self.s1_val.text(),'driverName': self.s2_val.text(),'aadharID': self.s3_val.text(),'driverPhone': self.s4_val.text(),'Age': self.s5_val.text()}
         Data1 = {'systemID': self.s1_val.toPlainText()}
         self.personaldata = json.dumps(self.s1_val.text())
         print ("personal json ready")

   def display(self,i):
      self.Stack.setCurrentIndex(i)

   def on_takephoto(self):
      self.showImage('photo.jpg')
   def getFinger(self):
      return self.takeFinger 
   def setFinger(self):
      self.takeFinger = True

The error is:

    <class 'PyQt4.QtCore.QString'>
    Traceback (most recent call last):
      File "/home/hearthacker/Desktop/gui code sagar/stacked.py", line 138, in personalData
        self.personaldata = json.dumps(self.s1_val.text())
      File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps
        return _default_encoder.encode(obj)
      File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
        return _iterencode(o, 0)
      File "/usr/lib/python2.7/json/encoder.py", line 184, in default
        raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: PyQt4.QtCore.QString(u's') is not JSON serializable

回答1:


If you use PyQt5, or Python3 with PyQt4, you will not get this kind of error, because PyQt will always return ordinary Python types whenever possible. But you are using Python2 with PyQt4, which means you have to explicitly request that behaviour.

To do that, change your imports as follows:

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *

(And note that the setapi calls must go before the first import of any PyQt modules in your application).

With that in place, you will also need to simplify your code to this:

   def personalData(self):
      print type(self.s1_val.text())
      if not self.s1_val.text():
         print "s1 is empty"
         #self.popup_window()
      if not self.s2_val.text():
         print "s2 is empty"
      if not self.s3_val.text():
         print "s3 is empty"
      if not self.s4_val.text():
         print "s4 is empty"
      if not self.s5_val.text():
         print "s5 is empty"

      if self.s1_val.text() and self.s2_val.text():
         Data1 = {'systemID': self.s1_val.text()}
         self.personaldata = json.dumps(Data1)
         print ("personal json ready")

PS:

If you're just starting out learning Python and/or PyQt, I would strongly recommend that you use Python3 and PyQt5 if at all possible.



来源:https://stackoverflow.com/questions/40903703/pyqt-data-is-not-json-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!