将列表中的项目更改为json中的键 [英] Change item in a list to a key in json

查看:98
本文介绍了将列表中的项目更改为json中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的字段列表-

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中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆