如何删除 JSON 数组中数字的小数位?

如何删除 JSON 数组中数字的小数位?

可以在脚本中发出什么 shell 命令bash来有效地从 JSON 文件中的数字中去除所有小数位,如下所示:

    [
        {
            "IMSKU": "1000001", 
            "AttributeID": 7332.0, 
            "Value": "McAfee Host Intrusion Prevention for Desktops safeguards your business against complex security threats that may otherwise be unintentionally introduced or allowed by desktops and laptops. Host Intrusion Prevention for Desktops is easy to deploy, configure, and manage.", 
            "Unit": null, 
            "StoredValue": null, 
            "StoredUnit": null, 
            "Name": "Marketing text", 
            "Format": "1", 
            "Position": "1", 
            "Group_Name": "Basic Specification", 
            "AGGroup_Position": 0.0, 
            "Product_Hierarchy": 15198001453.0
        }, 
        {
            "IMSKU": "1000001", 
            "AttributeID": 7343.0, 
            "Value": "May 2013", 
            "Unit": null, 
            "StoredValue": null, 
            "StoredUnit": null, 
            "Name": "PI Date", 
            "Format": "1", 
            "Position": "1", 
            "Group_Name": "PI DATE", 
            "AGGroup_Position": 1.0, 
            "Product_Hierarchy": 15198001453.0
        }, 
        {
            "IMSKU": "1000001", 
            "AttributeID": 7344.0, 
            "Value": "McAfee", 
            "Unit": null, 
            "StoredValue": "0.00", 
            "StoredUnit": null, 
            "Name": "Brand Name", 
            "Format": "3", 
            "Position": "1", 
            "Group_Name": "PRODUCT", 
            "AGGroup_Position": 2.0, 
            "Product_Hierarchy": 15198001453.0
        }
    ]

以便

"AttributeID":  7344.0

会成为

"AttributeID":  7344

例如,等等。

答案1

只需通过身份过滤器运行它,并将jq具有小数的数字重新格式化.0为整数:

$ jq . file.json
[
  {
    "IMSKU": "1000001",
    "AttributeID": 7332,
    "Value": "McAfee Host Intrusion Prevention for Desktops safeguards your business against complex security threats that may otherwise be unintentionally introduced or allowed by desktops and laptops. Host Intrusion Prevention for Desktops is easy to deploy, configure, and manage.",
    "Unit": null,
    "StoredValue": null,
    "StoredUnit": null,
    "Name": "Marketing text",
    "Format": "1",
    "Position": "1",
    "Group_Name": "Basic Specification",
    "AGGroup_Position": 0,
    "Product_Hierarchy": 15198001453
  },

(etc.)

如果有小数位不为零的数字,并且您也想删除它们,请使用

jq '(.. | select(type == "number" )) |= floor' file.json

这会将floor函数应用于数据中的所有数字,并将它们向下舍入到最接近的整数。

还要调查末尾的点后面是否有包含数字的字符串,并删除这些数字(和点):

jq '(.. | select(type == "string")) |= sub("\\.[0-9]+$"; "")' file.json

受影响的条目仍然是字符串,并且不会转换为数字类型。

相关内容