実現したいこと
json形式のデータをfor分を使ってsqliteに登録をpythonを使用して実現したい
前提
ServiceNowというSaaS(PaaS)に存在するデータをAPIで取得(JSON形式でレスポンス)し、
JSON形式で取得したデータをsqliteに登録したいが、vscodeでエラーが出てしまう。
エラーが発生せずに実行したい。
APIで取得できるJSONでの以下データの"P1000165"、"lnux100"、"2022-03-28 08:00:00"を
sqliteに登録したいです。
{
"result": [
{
"asset_tag": "P1000165",
"name": "lnux100",
"install_date": "2022-03-28 08:00:00"
}
]
}
発生している問題・エラーメッセージ
変数dataは定義しているはずですが、以下がエラーメッセージが出力されます。
for item in data["result"]:
^^^^
NameError: name 'data' is not defined
該当のソースコード
#Need to install requests package for python
#easy_install requests
import requests
import sqlite3
Set the request parameters
Eg. User name="admin", Password="admin" for this code sample.
user = 'xxxxx'
pwd = 'xxxxx'
Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
Check for HTTP codes other than 200
if response.status_code != 200:
Decode the JSON response into a dictionary and use the data
data = response.json()
conn = sqlite3.connect("/Users/xxxx/Desktop/xxxxx.db")
cursor = conn.cursor()
for item in data["result"]:
field1 = item["asset_tag"] # テーブルのレコードからの値を取得
field2 = item["name"] # テーブルのレコードから値を取得
field3 = item["install_date"] # テーブルのレコードから値を取得
conn.execute("INSERT INTO linux_table VALUES (field1, field2, field3)")
conn.commit()
conn.close()

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/06/04 05:53