将列表中的项更改为json中的键

时间:2016-07-07 14:11:13

标签: python json python-2.7

我有一个像这样的字段列表 -

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。如果我执行以下操作:

for server in server_list:
    for item in required_fields:
        print item

所有操作都是从键中的每个项返回字符串值。我想要它做的是给我与键相关的值。

以上代码中的示例print item给了我server['server_name']而不是torservapp001

2 个答案:

答案 0 :(得分:3)

这是另一种方法。请注意,它的工作原理是您的内容总是 server[<key>][<key>][...]

import ast

def parse_fields(field):
    field = field[6:]  # remove leading "server"
    field = field[1:-1]  # remove leading/trailing "[" and "]"
    fields = field.split('][')  # split at intermediate "]["
    return [ast.literal_eval(field) for field in fields]  # parse keys, e.g. 'foobar' to str foobar

然后你可以直接使用这些键:

for server in server_list:
  for item in required_fields:
    value = server
    for key in parse_fields(field):
        value = value[key]
    print item, value

当然,你也可以写parse_fields更短:

def parse_fields(fields):
  return [ast.literal_eval(field) for field in fields[7:-1].split('][')]

答案 1 :(得分:-1)

您要找的是eval

for server in server_list:
  for item in required_fields:
    print(eval(item))

eval将“运行”一个字符串,就像它是普通代码一样。例如,

eval('print("foo")')
print("foo")

两者都给出相同的结果。

强制性注意:如果要执行的代码源可能不受信任,请不要使用eval。在这种情况下,请参阅其他答案,或者如果您不确定。