Accessing JSON elements

前端 未结 5 1549
我寻月下人不归
我寻月下人不归 2020-11-30 23:19

I am getting the weather information from a URL.

weather = urllib2.urlopen(\'url\')
wjson = weather.read()

and what I am getting is:

相关标签:
5条回答
  • 2020-11-30 23:54
    import json
    weather = urllib2.urlopen('url')
    wjson = weather.read()
    wjdata = json.loads(wjson)
    print wjdata['data']['current_condition'][0]['temp_C']
    

    What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by json.loads and then you can parse it with index.

    Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:

    wjdata = json.load(urllib2.urlopen('url'))
    
    0 讨论(0)
  • 2020-11-30 23:59

    Another alternative way using get method with requests:

    import requests
    wjdata = requests.get('url').json()
    print wjdata.get('data').get('current_condition')[0].get('temp_C')
    
    0 讨论(0)
  • 2020-12-01 00:00

    Here's an alternative solution using requests:

    import requests
    wjdata = requests.get('url').json()
    print wjdata['data']['current_condition'][0]['temp_C']
    
    0 讨论(0)
  • 2020-12-01 00:02

    'temp_C' is a key inside dictionary that is inside a list that is inside a dictionary

    This way works:

    wjson['data']['current_condition'][0]['temp_C']
    >> '10'
    
    0 讨论(0)
  • 2020-12-01 00:05

    Just for more one option...You can do it this way too:

    MYJSON = {
        'username': 'gula_gut',
        'pics': '/0/myfavourite.jpeg',
        'id': '1'
    }
    
    #changing username
    MYJSON['username'] = 'calixto'
    print(MYJSON['username'])
    

    I hope this can help.

    0 讨论(0)
提交回复
热议问题