简体   繁体   中英

Python JSON to array & PyQt QListWidget

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?

You got your array of names in data[resp] . You can do this to add long_name s 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM