1

Just starting out here, hopefully this is simple and someone can push me in the right direction.

  1. What I have is a weather API that returns a lot of data I don't need.
  2. I can pull the relevant information into a smaller json dict, this works
  3. What I want to do, is set the values from the dict as variables so that everytime this runs, the variables are assigned new data

    import requests
    import json
    from requests.auth import HTTPBasicAuth
    import datetime
    import time
    from datetime import datetime
    
    weatherString = requests.get('https://twcservice.mybluemix.net/api/weather/v1/geocode/33.40/-83.42/observations.json?language=en-US&units=e', auth=HTTPBasicAuth('user','pass'))
    
    data=weatherString.json()
    
    result = {
    "Hum": data['observation']['rh'],
    "Pressure": data['observation']['pressure'],
    "DewPt": data['observation']['dewPt'],
    "Temp": data['observation']['temp'],
    "Time": datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
     }
    
    final = json.dumps(result)
    print(final)
    

In short, I would like Hum, Pressure, DewPt, Temp, and Time to be variables instead of keys in a dict if that makes sense.

Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
woodside
  • 53
  • 1
  • 4
  • 2
    Why do you need them as variables? Namespaces are great! – iz_ Dec 05 '18 at 03:16
  • There is another function in the larger code that creates a JSON dict from another data source and I want to essentially append this JSON to that one. – woodside Dec 05 '18 at 03:18
  • 1
    Possible duplicate of [Python: load variables in a dict into namespace](https://stackoverflow.com/questions/2597278/python-load-variables-in-a-dict-into-namespace) – iz_ Dec 05 '18 at 03:18
  • Appending two JSONs definitely doesn't require you to make them local variables. – iz_ Dec 05 '18 at 03:19
  • Running `globals().update(result)` will do what you want. However, it is not advisable to do this in general. – hilberts_drinking_problem Dec 05 '18 at 03:25

2 Answers2

0

You could assign directly to the variable, the values of which should already be typed.

data=weatherString.json()

data = json.loads(data)

Hum = data['observation']['rh']
Pressure = data['observation']['pressure']
DewPt = data['observation']['dewPt']
Temp = data['observation']['temp']
Time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
danetrata
  • 9
  • 4
0

If you want the data as "variables" instead of "keys", you could use something like the DictObject I proposed for a similar situation, passing in data['observation'] (though you would need to synthesize Time separately and you wouldn't get the name remapping that you are implying in your question).

B. Morris
  • 630
  • 3
  • 15