簡體   English   中英

如何通過jq命令將json文件中的所有整數轉換為字符串?

[英]How to convert all integers in a json file to strings via jq command?

假設我們有一個a.json文件。 該文件包含許多屬性。 例如,在文件中,我僅顯示兩個屬性“名稱”和“年齡”。 實際上,盡管有更多具有數值的屬性。

{
  "name":[
    "James", 
    "Alek", 
    "Bob"
  ],
  "age":[
    35,
    25,
    23
  ]
  ...//other attributes with numerical values
} 

我們如何像下面這樣轉換文件?

{
  "name":[
    "James", 
    "Alek", 
    "Bob"
  ],
  "age":[
    "35",
    "25",
    "23"
  ]
  ...//other attributes with numerical values
} 

jq解決方案

您可以使用jq的內置walk()來遞歸遍歷JSON值,檢查其type s並將數字轉換為tostring()

假設您的JSON存儲在文件input.json ,則命令類似於:

jq 'walk(if type == "number" then tostring else . end)' input.json

它將修改后的JSON轉儲到屏幕上,其輸出可以重定向到另一個文件( > output.json )。

如果失敗

最有可能的是,以上命令失敗並顯示錯誤消息:

jq: error: walk/1 is not defined at <top-level>, line 1:

這意味着內置的walk()不是您所使用的jq版本中內置的(!)。 該問題已在兩年前報告(問題#1106 ),但顯然不是錯誤,而是可選功能。 內置的定義可以從Github的項目頁面下載 一旦下載並保存到本地文件中,內置模塊就可以使用include()加載並使用。

您的工作流程如下所示:

# Download the builtins module (only once) and save it in './builtin.jq'
curl -O https://raw.githubusercontent.com/stedolan/jq/master/src/builtin.jq

# Process the data
jq 'include "./builtin"; walk(if type == "number" then tostring else . end)' input.json > output.json

就這樣!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM