Get json data via url and use in python (simplejson)

后端 未结 3 882
不思量自难忘°
不思量自难忘° 2021-01-30 02:38

I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the la

相关标签:
3条回答
  • 2021-01-30 03:00

    The first line reads the entire file. The second line then tries to read more from the file, but there's nothing left:

    >>> f.read()             # this works
    blah blah blah
    >>> simplejson.load(f)
    

    Either just omit the f.read() line, or save the value from read, and use it in loads:

    json = f.read()
    simplejson.loads(json)
    
    0 讨论(0)
  • 2021-01-30 03:07

    Try

    f = opener.open(req)
    simplejson.load(f)
    

    without running f.read() first. When you run f.read(), the filehandle's contents are slurped so there is nothing left when your call simplejson.load(f)

    0 讨论(0)
  • 2021-01-30 03:18

    There's an even easier way - you dont need simplejson at all. Python can parse json into a dict/array using the eval statement as long as you set true/false/null to the right values.

    # fetch the url
    url = "https://api.twitter.com/1/users/lookup.json?user_id=6253282,18949452"
    json = urllib2.urlopen(url).read()
    
    # convert to a native python object
    (true,false,null) = (True,False,None)
    profiles = eval(json)
    
    0 讨论(0)
提交回复
热议问题