聚合数组属性并转换为csv

时间:2018-11-05 22:46:42

标签: arrays json csv sum jq

我有以下文件(vms.json),我正在尝试在添加磁盘大小元素的同时转换csv。

vms.json

hostname,state,platform,Disks
host1,running,linux,62277025792
host2,running,linux,39519165044

vms.csv

    import pygame
    from settings import Settings
    from ship import Ship
    import game_functions as gf

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    ship = Ship(ai_settings,screen)
    bullets = pygame.sprite.Group()
    aliens = pygame.sprite.Group()

    gf.create_fleet(ai_settings,screen,ship,aliens)

    while 1:
        gf.check_events(ai_settings,screen,ship,bullets)
        ship.update()
        gf.update_bullet(bullets)
        gf.update_alien(ai_settings,aliens)
        gf.update_screen(ai_settings,screen,ship,bullets,aliens)

run_game()

我想使用jq执行此转换,但是 如何使用jq和@csv过滤器来实现?

1 个答案:

答案 0 :(得分:1)

给出您的输入和使用-r选项调用jq的以下过滤器:

 .vms[]
| [.hostname, .state, .platform, (.Disks | map(.size|tonumber) | add)]
| join(",")

产生:

host1,running,linux,62277025792
host2,running,linux,39519165044

添加标题,并探索当join(",")@csv代替时会发生什么:-)