问题描述
我有类似的字段列表-
required_fields = ["server['server_name']","server['server_info']['asset_type']['display_name']",
"server['asset_status']['display_name']", "server['record_owner']['group_name']",
"server['server_total_cost_of_ownership']['description']",
"server['primary_business_owner']['name']", "server['environment']['display_name']",
"server['is_virtual']", "server['managed_by']['display_name']",
"server['server_info']['billable_ibm']", "server['server_info']['billing_sub_type']['display_name']",
"server['server_info']['serial_number']", "", "server['location']['display_name']",
"server['inception_date']", "server['server_info']['decommission_date']" ]
每个代表一个JSON文件中的键,我想获取其中的值以转换为CSV.如果我执行以下操作:
Each one represents a key in a JSON file I want to get the values out of to transform into CSV. If I do the following:
for server in server_list:
for item in required_fields:
print item
所有要做的就是从键中的每个项目返回字符串值.我要它做的就是为我提供与键关联的值.
all is does is return the string value from each item in the key. What I want it to do is give me the value that is associated with the key.
因此,例如上面的代码print item
给我server['server_name']
而不是torservapp001
So as an example in the above code print item
is giving me server['server_name']
and not torservapp001
推荐答案
您正在寻找的是 eval
:
What you are looking for is eval
:
for server in server_list:
for item in required_fields:
print(eval(item))
eval
将运行"一个字符串,就好像它是纯代码一样.例如,
eval
will "run" a string as if it were plain code. For example,
eval('print("foo")')
print("foo")
两者给出相同的结果.
必填项:如果要执行的代码源可能不受信任,请不要使用eval
.在这种情况下,或者如果您不确定,请查看其他答案.
Mandatory Note: Please don't use eval
if the source of the code to execute is potentially untrusted. See the other answer in this case, or if you are unsure.
这篇关于将列表中的项目更改为json中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!