将 JSON 转换为表,标题为“Key”和“Value”

将 JSON 转换为表,标题为“Key”和“Value”

我有以下 JSON 输出:

 [
  {
    "enabled": "true",
    "policy_profile": "custom",
    "scan_local_files": "true",
    "local_file_types": "all",
    "scan_network_files": "false",
    "limit_file_size": "false",
    "enable_archive_scanning": "false",
    "scan_boot_sectors": "true",
    "scan_only_new_changes": "true",
    "scan_for_keyloggers": "true",
    "scan_for_puas": "true",
    "deferred_scanning": "true",
    "scan_action_for_infected_files": "Move to quarantine",
    "scan_action_for_infected_files_secondary": "Move to quarantine",
    "scan_action_for_suspect_files": "Move to quarantine",
    "scan_action_for_suspect_files_secondary": "Deny Access"
  }
]

我一直在努力让输出看起来像一个逆表。我可以让它看起来像下面这样:

deferred_scanning       enable_archive_scanning enabled limit_archive_size      limit_file_size local_file_types        max_archive_depth       policy_profile  scan_action_for_infected_files  scan_action_for_infected_files_secondary   scan_action_for_suspect_files   scan_action_for_suspect_files_secondary scan_boot_sectors       scan_for_keyloggers     scan_for_puas   scan_local_files  scan_network_files       scan_only_new_changes
-----------------       ----------------------- ------- ------------------      --------------- ----------------        -----------------       --------------  ------------------------------  ----------------------------------------   -----------------------------   --------------------------------------- -----------------       -------------------     -------------   ----------------  ------------------       ---------------------
true    true    true    5       false   all     6       custom  Move to quarantine      Move to quarantine      Move to quarantine      Deny Access     true    true    true    true    false   true

但这有点乱,我想要这样的东西:

Attribute           Value
---------           -----
enabled             true
policy_profile      custom
scan_local_files    true
...

任何帮助或指出涵盖此特定问题的现有 SE 问题将不胜感激。

答案1

这似乎适用于您的输入数据

jq -r '.[] | to_entries[] | [.key,.value] | @tsv' file.json

输出(制表符分隔):

enabled true
policy_profile  custom
scan_local_files        true
local_file_types        all
scan_network_files      false
limit_file_size false
enable_archive_scanning false
scan_boot_sectors       true
scan_only_new_changes   true
scan_for_keyloggers     true
scan_for_puas   true
deferred_scanning       true
scan_action_for_infected_files  Move to quarantine
scan_action_for_infected_files_secondary        Move to quarantine
scan_action_for_suspect_files   Move to quarantine
scan_action_for_suspect_files_secondary Deny Access

然后使用相对简单的awk工具或其他工具以您想要的任何方式对其进行格式化。

如果您希望将AttributeValue列为第一行,请像这样更改命令

jq -r  '[ "Attribute", "Value"], ( .[] | to_entries[] | [.key,.value] ) | @tsv' file.json

参考jq:打印对象中每个条目的键和值,刚刚向我介绍了to_entries

相关内容