【发布时间】:2021-12-08 17:19:21
【问题描述】:
试图找出正确的语法来遍历列表以获取所有值并插入到 oracle 中。
编辑: 下面是json结构:
[{
"publishTime" : "2021-11-02T20:18:36.223Z",
"data" : {
"DateTime" : "2021-11-01T15:10:17Z",
"Name" : "x1",
"frtb" : {
"code" : "set1"
},
"mainAccounts" : [ {
"System" : {
"identifier" : {
"domain" : "System",
"id" : "xxx"
},
"name" : "TEST1"
},
"Account" : "acc1"
}, {
"System" : {
"identifier" : {
"domain" : "System",
"id" : "xxx"
},
"name" : "TEST2"
},
"Account" : "acc2"
}, {
"System" : {
"identifier" : {
"domain" : "System",
"id" : "xxx"
},
"name" : "TEST3"
},
"Account" : "acc3"
}],
"sub" : {
"ind" : false,
"identifier" : {
"domain" : "ops",
"id" : "1",
"version" : "1"
}]
我的python代码:
insert_statement = """INSERT INTO mytable VALUES (:1,:2)"""
r =requests.get(url, cert=(auth_certificate, priv_key), verify=root_cert, timeout=3600)
data=json.loads(r.text)
myrows = []
for item in data:
try:
name = (item.get("data").get("Name"))
except AttributeError:
name=''
try:
account= (item.get("data").get("mainAccounts")[0].get("Account") )
except TypeError:
account=''
rows=(name,account)
myrows.append(rows)
cursor.executemany(insert_statement,myrows)
connection_target.commit()
上面我只得到列表中“帐户”的第一个值,即 ("acc1") ,如何获取所有值,即 (acc1,acc2,acc3) ?
我在下面尝试过但没有成功:
尝试: Account = (item.get("data").get("mainAccounts")[0].get("Account") for item in data["mainAccounts") 除了类型错误: 帐户=''
请多多指教。感谢您的帮助。
【问题讨论】:
-
for item in data: accounts = [act["Account"] for act in item.get("data", {}).get("mainAccounts", [])]?我能问一下您为什么在这里期待TypeError吗? -
抱歉语法无效
-
你把它放在哪里?对于您的第一行
for item in data:。对于您的第二行accounts = [act["Account"] for act in item.get("data", {}).get("mainAccounts", [])]。没有try/except。就在你定义data之后的那两行代码。 -
如果您仍然有问题,我会将其作为格式化答案发布。
-
对不起,我尝试过/除了。我正在尝试将此数据输入 oracle ,现在我得到“cx_Oracle.NotSupportedError:OCI 不支持数组数组