Python 3 Get and parse JSON API

前端 未结 5 1174
醉梦人生
醉梦人生 2021-01-31 14:58

How would I parse a json api response with python? I currently have this:

import urllib.request
import json

url = \'https://hacker-news.firebaseio.com/v0/topsto         


        
5条回答
  •  日久生厌
    2021-01-31 15:07

    The only thing missing in the original question is a call to the decode method on the response object (and even then, not for every python3 version). It's a shame no one pointed that out and everyone jumped on a third party library.

    Using only the standard library, for the simplest of use cases :

    import json
    from urllib.request import urlopen
    
    
    def get(url, object_hook=None):
        with urlopen(url) as resource:  # 'with' is important to close the resource after use
            return json.load(resource, object_hook=object_hook)
    

    Simple use case :

    data = get('http://url') # '{ "id": 1, "$key": 13213654 }'
    print(data['id']) # 1
    print(data['$key']) # 13213654
    

    Or if you prefer, but riskier :

    from types import SimpleNamespace
    
    data = get('http://url', lambda o: SimpleNamespace(**o)) # '{ "id": 1, "$key": 13213654 }'
    print(data.id) # 1
    print(data.$key) # invalid syntax
    # though you can still do
    print(data.__dict__['$key'])
    

提交回复
热议问题