【问题标题】:parsing string or json in bash (shell)在 bash (shell) 中解析字符串或 json
【发布时间】:2015-02-04 19:19:31
【问题描述】:

请帮帮我。

我有字符串(json请求):

{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}

我尝试用命令解析它:

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`

还有[{u'hostid': u'10158'}]

我如何只能得到 10158(如示例)

谢谢。

附:这也行不通:

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]["hostid"]'`

【问题讨论】:

  • result 是一个列表。您需要先对其进行索引,然后才能获取hostid。 (第二个例子的错误应该已经提示你了。)试试...["result"][0]["hostid"]'

标签: python json bash shell


【解决方案1】:

在您的示例中,result 是一个数组。要获取hostid,您需要指定项目索引:

json.load(sys.stdin)["result"][0]["hostid"]

所以你的代码应该是这样的:

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"][0]["hostid"]'`

【讨论】:

    【解决方案2】:

    试试jq。这是在 shell 中解析 JSON 的最简单方法。

    $ jq -r '.result[0].hostid' <<< "$json"
    10158
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2017-07-29
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多