whoisearth whoisearth - 5 months ago 9
JSON Question

Change item in a list to a key in json

I have a list of fields like so -

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']" ]


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.

So as an example in the above code
print item
is giving me
server['server_name']
and not
torservapp001

Answer

What you are looking for is eval:

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

eval will "run" a string as if it were plain code. For example,

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

both give the same result.

Mandatory Note: Don't use eval if the source of the code to execute is potentially untrusted.