我被赋予了一个从url读取json然后在python中解析它的任务。每个字段都将分配给一个变量来存储该值。然后将该值存储到postgres表中。
Json的例子
{
"forecasts":
[
{
"class": "fod_long_range_daily",
"expire_time_gmt": 1525126617,
"night": {
"fcst_valid": 1525158000,
"fcst_valid_local": "2018-05-01T19:00:00+1200",
"golf_category": ""
},
"day": {
"uv_warning": 0,
"uv_desc": "Moderate",
"golf_index": 10,
"golf_category": "Excellent"
}
}
]
}
我被告知这样我可以解析json并将其读入postgres。我能否知道我是否采取了正确的方式?是否存在性能问题?
风格1:
import urllib3
import psycopg2
import json
conn = psycopg2.connect(host="localhost", database="nzaus",
user="admin", password="123321")
print("Database Connected")
cur = conn.cursor()
rowcount = cur.rowcount
http = urllib3.PoolManager()
url = "https://api.data.com/v1/geocode/-35.228208/174.095969/forecast/daily/15day.json?language=en-US&units=m&apiKey=1234"
try:
response = http.request('GET', url)
data = json.loads(response.data.decode('utf-8'))
for item in data['forecasts']:
class = None
time = None
fcst_valid = None
golf_category = None
result = []
class = item['class']
time = item['expire_time_gmt']
fcst_valid = item['night']['fcst_valid']
golf_category = item['morning']['golf_category']
result = [class,time,fcst_valid,golf_category]
cur.execute("""INSERT into datatable
VALUES
( %s,
%s,
%s,
%s,
)""",(result))
conn.commit()
cur.close()
except IOError as io:
print("cannot open")