【问题标题】:jq: error (at <stdin>:1): Cannot index array with string "name" SOLVEDjq:错误(在 <stdin>:1):无法使用字符串“名称”索引数组 已解决
【发布时间】:2020-06-30 06:06:10
【问题描述】:

我正在尝试创建一个包含国家、地区、城市、组织、入侵尝试 IP 的 JSON 集合。

我的 JSON 测试信息:

[
  {
    "total": 0,
    "country": [
      {
        "name": "CN",
        "nr": 0,
        "region": [
          {
            "name": "Beijing",
            "nr": 0,
            "City": [
              {
                "name": "Haidian",
                "nr": 0,
                "Organisation": [
                  {
                    "name": "AS45090 Shenzhen Tencent Computer Systems Company Limited",
                    "nr": 0,
                    "IPS": [
                      {
                        "192.144.207.22": 0
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        "name": "NL",
        "nr": 0,
        "region": [
          {
            "name": "Noord Holland",
            "nr": 0,
            "City": [
              {
                "name": "Amsterdam",
                "nr": 0,
                "Organisation": [
                  {
                    "name": "FEAS",
                    "nr": 0,
                    "IPS": [
                      {
                        "192.162.1.1": 0
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
 }
]

我将现有的 json(测试)字符串加载到 $geoInfo。现在我正在尝试更改对象 where"name": "CN" 中的 nr 值

我已经测试了两种解决方案:

geoInfo="$( jq --arg country ${tmpGeo[0]} --arg count $count -r '.country | map( if .name == $country then . + { .nr=$count } else . end )'&lt;&lt;&lt;"${geoInfo}" )"

geoInfo="$( jq --arg country ${tmpGeo[0]} --arg count $count -r '.country | select(.[].name == "CN") | .nr) = $count'&lt;&lt;&lt;"${geoInfo}" )"

通过这两种解决方案,我得到: jq: error (at &lt;stdin&gt;:1): Cannot index array with string "name"

我使用 jq 1.6 版。

出了什么问题?

【问题讨论】:

  • tmpGeo的内容是什么? count?向我们展示您期望达到的输出的确切输入

标签: arrays json string bash jq


【解决方案1】:

请您尝试以下方法:

geoInfo=$(jq "(.[].country[] | select(.name == \"CN\") | .nr) = 1" <<<"$geoInfo")

【讨论】:

    【解决方案2】:

    忘记这一切吧!我非常抱歉。我得到的错误是 else 部分中的一条语句,我正在更改 then 部分中的查询。昨天可能在代码上工作了很长时间。在将.nr= 更改为"nr": 后,我的第一个解决方案出现了一个小错误:

    geoInfo="$( jq --arg country ${tmpGeo[0]} --arg count $count -r '.country | map( if .name == $country then . + { "nr": $ count } else .end )'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 2018-01-14
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多