whoisearth whoisearth - 1 year ago 72
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['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
and not

Answer Source

What you are looking for is eval:

for server in server_list:
  for item in required_fields:

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


both give the same result.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download