jq 相当于 python

问题描述 投票:0回答:2
cat * | jq '.cis[].properties.cloud_vm_display_name' | grep -v null

“azuXXXXX” “azuXXXXXX” “azuXXXXXX” “azuXXXXXX”

需要从多个json文件中提取云虚拟机名称,每个文件中的数组编号不同。

a = data1['cis'][0]['properties']['TenantsUses'][0]
print(a)
b = data1['cis'][]['properties']['cloud_vm_display_name']
File "<stdin>", line 17
b = data1['cis'][]['properties']['cloud_vm_display_name']
                 ^
SyntaxError: invalid syntax

print(a) 提供了正确的输出,但变量 b 的值 [] 未知,需要您的支持来查找输出。

从为不同服务器生成的各种 json 文件中查找 VM 名称。

python arrays json jq
2个回答
0
投票

Python 有可以在此处使用的循环(和列表推导式)。

b = []
for cis in data1['cis']:
  name = cis['properties']['cloud_vm_display_name']
  if not 'null' in name:
    b.append(name)
print(b)

通过列表理解:

b = [cis['properties']['cloud_vm_display_name'] for cis in data1['cis'] if not 'null' in cis['properties']['cloud_vm_display_name']]

或用于准备数据的生成器表达式和用于过滤所需名称的列表理解:

names = (cis['properties']['cloud_vm_display_name'] for cis in data1['cis'])
b = [name for name in names if not 'null' in name]

请注意,这实现了与您的

grep
示例相同的行为:任何位置包含 null 的名称(例如“nullified”或“annulled”)都不会成为结果列表的一部分。您可能分别指的是
grep -vx
name == 'null'
。更好的是,根本不使用 grep,而是直接使用 jq 进行过滤:
.cis[].properties.cloud_vm_display_name | values
.


0
投票

我的要求是收集部署在 Azure 中的 Windows 服务器的文件系统详细信息。 CMDB 工具正在收集所有 Windows 服务器的完整信息,但通过 API 调用获取所需信息并不成功,因为每个服务器的属性编号都不同,因此,我使用以下机制来检索数据。 感谢所有成员的建议,可能是我无法正确描述我的问题。

    cis[103].properties.mount_point --> for one server
    cis[333].properties.mount_point --> for another server
    cis[348].properties.mount_point

我使用以下方法进行管理:-

for line in cidet:
 line_number += 1
 target_number = '"type" : "file_system"'
 if target_number in line:
      fir_num = line_number
      last_num = fir_num + 40
      lin1 = fir_num + 20
      lin2 = fir_num + 22
      lin3 = fir_num + 36
      mt_pt = open("/home/"+udcid+"","r").readlines()[lin1]
      mt_pt = mt_pt.strip('"mount_point" : "')
      mt_pt = mt_pt.strip('",\n')
      dk_sz = open("/home/"+udcid+"","r").readlines()[lin2]
      dk_sz = dk_sz.strip('"disk_size" : "')
      dk_sz = dk_sz.strip('",\n')
      fr_sp = open("/home/a"+udcid+"","r").readlines()[lin3]
      fr_sp = fr_sp.strip('"free_space" : "')
© www.soinside.com 2019 - 2024. All rights reserved.