Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new JSON in Python from subset of larger JSON

I'm new to python and am trying to do the following in Google Cloud Functions

1) Call an API to return JSON weather data

2) Extract relevant pieces of the returned data and create a new simple JSON

3) Publish JSON to BigQuery table

import requests
import json
from requests.auth import HTTPBasicAuth

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()

print("Hum",data['observation']['rh'])
print("Pressure",data['observation']['pressure'])
print("DewPt",data['observation']['dewPt'])
print("Temp",data['observation']['temp'])

This works to print the values from the keys but what I'm trying to do is create a new JSON object using these pairs. Any help greatly appreciated!

like image 234
woodside Avatar asked Oct 22 '25 09:10

woodside


1 Answers

There's no such thing as a "JSON object" in Python -- what you're trying to create is a dict:

result = {
    "Hum": data['observation']['rh'],
    "Pressure": data['observation']['pressure'],
    "DewPt": data['observation']['dewPt'],
    "Temp": data['observation']['temp'],
}

This can then be serialized to a JSON string as follows:

json.dumps(result)
like image 122
Dustin Ingram Avatar answered Oct 24 '25 00:10

Dustin Ingram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!