Python JSON to array & PyQt QListWidget

3.5k views Asked by At

My problem is: I call the server API and the answer is a JSON file (with base64 encode) I would like to convert JSON to array and I would like to use this array to the PyQt QListWidget.

PyQt list example:

Line1: TEST1-TEST NAME1
Line2: TEST2-TEST NAME2
Line3: TEST3-TEST NAME3
etc.

This is my code base64 decode after:

text_json=base64.b64decode(response)
data=json.loads(text_json)
print(data)

This is the JSON (data):

{u'resp': [{u'short_name': u'TEST1', u'long_name': u'TEST NAME1'}, 
{u'short_name': u'TEST2', u'long_name': u'TEST NAME2'}, 
{u'short_name': u'TEST3', u'long_name': u'TEST NAME3'}]}

This is my PyQt code:

self.List=QtGui.QListWidget(self)
self.List.resize(500,500)
self.List.move(0,0)
self.List.addItem()
self.List.show()

My problem: I would like to convert JSON to array but this JSON file is in unicode format. My plan: If I have the array, I know the number of arrays. I can add the array elements to the PyQt list. (My biggest problem is Python dictionary) But how to convert JSON to array? Or how parsing in Python dictionary? Or is there any simplyer solution?

2

There are 2 answers

0
mkhanoyan On BEST ANSWER

You got your array of names in data[resp]. You can do this to add long_names to your list:

self.List=QtGui.QListWidget(self)
self.List.resize(500,500)
self.List.move(0,0)
for person in data["resp"]:
    item = QtGui.QListWidgetItem(person["long_name"])
    self.List.addItem(item)
self.List.show()

Here is some documentation that might help.

0
ekhumoro On

You can just load the data straight into the list-widget like this:

for item in data['resp']:
    self.List.addItem('%(short_name)s - %(long_name)s' % item)

Unicode is not a problem, because json does all the conversion for you.