代码之家  ›  专栏  ›  技术社区  ›  Pathfinder

在bash中解析带有空格的JSON数组

  •  0
  • Pathfinder  · 技术社区  · 4 年前

    我试图解析下面的json数组并从中获取值。但它不能将空间作为值。我确实在 stackoverflow 但似乎没用。

    JSON格式

     {
      "apps": [
        {
          "name": "Root Certification Authority - G2",
          "expiryDate": "Monday, 09 October 2023 20:03:25",
          "impactStatement": "Apps using this root certificate will have an actual impact",
          "notifyBeforeInDays": 60
        },
        {
          "name": "Bamboo",
          "expiryDate": "Sunday, 20 November 2022 03:25:23",
          "impactStatement": "CI/CD wont be working",
          "sop": "https://somelink/Bamboo+SOPs",
          "notifyBeforeInDays": 30
        },
        {
          "name": "Vault - Client",
          "expiryDate": "Monday, 09 October 2023 20:03:25",
          "impactStatement": "All Mule applications for that particular environment will stop working",
          "notifyBeforeInDays": 60
        },
        {
          "name": "Consul",
          "expiryDate": "Monday, 21 August 2023 14:43:56",
          "impactStatement": "No Direct impact or never had any such scenario so far",
          "notifyBeforeInDays": 30
        },
        {
          "name": "bitbucket",
          "expiryDate": "08 September 2021 13:16:06",
          "impactStatement": "No Impact",
          "notifyBeforeInDays": 15
        }
      ]
    }
    

    我使用下面的代码来解析json

    appls=$(awk '{print $0}' ${work_dir}/scripts/applications.json | jq -c '. |select(.apps !=null) |.apps[]')
    echo "*****"
    echo $appls
    echo "*****"
    for row in ${appls}; do
      echo $row
      validateAndNotify $row
    done
    

    当我打印上面的变量时,下面的输出被打印出来,这是无效的。

    *****
     {"name":"bitbucket","expiryDate":"08 September 2021 13:16:06","impactStatement":"No Impact","notifyBeforeInDays":15} such scenario so far","notifyBeforeInDays":30}","notifyBeforeInDays":60}Bamboo+SOPs","notifyBeforeInDays":30}
    *****
    {"name":"Root
    

    我想解析apps数组并获取该节点内的每个值。

    1 回复  |  直到 4 年前
        1
  •  1
  •   hek2mgl    4 年前

    您需要在shell中引用变量以防止 word splitting :

    #!/bin/bash
    
    work_dir="/foo/bar"
    
    validateAndNotify() {
        echo "${1}"
    }
    
    appls=$(jq -c '.apps[]?' "${work_dir}/scripts/applications.json")
    
    echo "*****"
    echo "${appls}"
    echo "*****"
    while read -r row ; do
      validateAndNotify "${row}"
    done <<< "${appls}"
    

    jthill