【发布时间】:2021-03-05 07:53:22
【问题描述】:
我有一个 json_data 对象,如下所示:
{
"tables": [
{
"id": "49704565-7d73-11eb-9457-cc3d8278f653",
"name": { "singular": "category", "plural": "category" },
"fields": [
{
"id": "49704564-7d73-11eb-b772-cc3d8278f653",
"name": { "singular": "product", "plural": "products" },
"relation": { "entity": "" },
"type": "relation_many"
}
]
},
{
"id": "49704563-7d73-11eb-90f8-cc3d8278f653",
"name": { "singular": "product", "plural": "product" },
"fields": [
{
"id": "49704562-7d73-11eb-9d41-cc3d8278f653",
"name": { "singular": "category", "plural": "categories" },
"relation": { "entity": "" },
"type": "relation_one"
}
]
}
],
"properties": {
"name": "ProjetCRA"
}
}
现在,我定义了 2 个函数来获取“表的 ID”以及“字段的 ID”属于特定表:
def get_tbl_id(tbl_name, json_data):
tbl_id = ""
for e in json_data['tables']:
if (e['name']['singular'] == tbl_name):
tbl_id = e['id']
return tbl_id
def get_field_id(field_name, tbl_name, json_data):
field_id = ""
for e in json_data['tables']:
if (e['name']['singular'] == tbl_name):
for f in e['fields']:
if (f['name']['singular'] == field_name):
field_id = f['id']
return field_id
我可以在下面运行这些命令,它会返回我想要的结果:
get_tbl_id('category', json_data) => "49704565-7d73-11eb-9457-cc3d8278f653"
get_tbl_id('product', json_data) => "49704563-7d73-11eb-90f8-cc3d8278f653"
get_field_id('product', 'category', json_data) => "49704564-7d73-11eb-b772-cc3d8278f653"
get_field_id('category', 'product', json_data) => "49704562-7d73-11eb-9d41-cc3d8278f653"
现在,我有一个字符串
str_args = "cagetory-relation_many,product,product"
我会分开的:
table_need_to_update = str_args.split('-')[0]
table_will_be_refer_to = str_args.split('-')[1].split(',')[2]
如果我从命令中运行它,我会得到:
table_need_to_update => 'category'
table_will_be_refer_to => 'product'
但是,如果我运行:
get_tbl_id(table_need_to_update , json_data)
get_tbl_id(table_will_be_refer_to , json_data)
第一个结果我会得到空字符串:
我不知道为什么,虽然字符串 table_need_to_update 是 'category',如果我显式运行参数 'category',这行得通。请看看并帮助我。
【问题讨论】:
标签: arrays json python-3.x list