Json

將 JSON 轉換為表格,標題為“Key”和“Value”

  • May 2, 2022

我有以下 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 問題將不勝感激。

這似乎適用於您的輸入數據

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或其他一些工具以您想要的任何方式對其進行格式化相對簡單。

如果您希望AttributeandValue列為第一行,請像這樣更改命令

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

參考jq: print key and value for each entry in an object,剛剛介紹給我to_entries

引用自:https://unix.stackexchange.com/questions/701158