Python parses the json instance method

  • 2020-04-02 13:13:19
  • OfStack

Recently in the weather business delay monitoring, is every hour to check whether the weather data changes, three times no change on the alarm. Since the data given by the page is in json format, how to parse the data on the page to get the fields we want is our first consideration.
Generally speaking, when we take data from a web page, it is just a string, such as:


url_data = urllib2.urlopen(url).readline()


When we get the page data like this, url_data is a json string displayed on the whole page, so how can we convert this string to the dictionary format :time = json.load (url_data)["weatherinfo"]["time"]

The json module's function loads() encodes the original string as a dictionary, which makes it easier to find the key value of a field.
Part of the code is as follows:


def getTime(url):
        url_data = urllib2.urlopen(url).readline()
        print url_data
        time = json.loads(url_data)["weatherinfo"]["time"]
        return time


Related articles: