1

I have a json string and I am trying to print each section (id, name, link, etc) by using labels on tkinter GUI window.

Data:

{"id":"123456789","name":"John Smith","first_name":"John","last_name":"Smith","link":"http:\/\/www.facebook.com\/john.smith","username":"john.smith","gender":"male","locale":"en_GB"}

Code:

URL = https://graph.facebook.com/ + user
info = urlopen(info).read()
json_format = infor.decode("utf-8")

My problem is how do I assign each section of the json data to a variable do it can be printed out on a tkinter label?

thanks in advance

EDIT

Tried this code:

jsonData = json.loads(json_format)
u_name = jsoninfo['username']

and got the following error message

TypeError: string indices must be integers
user2148781
  • 129
  • 1
  • 1
  • 11

3 Answers3

6

You want to use the json standard module:

>>> import json
>>> data = '{"id":"123456789","name":"John Smith","first_name":"John","last_name":"Smith","link":"http:\/\/www.facebook.com\/john.smith","username":"john.smith","gender":"male","locale":"en_GB"}'
>>> d = json.loads(data)

This gives you your data as a regular dictionary to use:

>>> d
{u'username': u'john.smith', u'first_name': u'John', u'last_name': u'Smith', u'name': u'John Smith', u'locale': u'en_GB', u'gender': u'male', u'link': u'http://www.facebook.com/john.smith', u'id': u'123456789'}
>>> d['username']
u'john.smith'
icecrime
  • 74,451
  • 13
  • 99
  • 111
1
try:
    import simplejson as json
except ImportError: 
    import json

json_data = json.dumps(info)
# info here is json string or your variable json_format
Ellochka Cannibal
  • 1,750
  • 2
  • 19
  • 31
0

You need to import the json library - it is included in the standard library, and load the json. This will convert the json string to a Python dictionary which you can use.

import json

py_dict= json.loads(json_string)
# work away
elssar
  • 5,651
  • 7
  • 46
  • 71