【问题标题】:Parsing input argv json string解析输入 argv json 字符串
【发布时间】:2017-06-12 23:21:21
【问题描述】:

我想将 linux jq 调用的输出解析为一个 python 脚本,该脚本将解码输出 jq json str 并对其进行处理。

我的jq 调用jq '.geometry' myJson.json 的输出是这样的:

{
  "coordinates": [
    [
      [
        5,
        2
      ],
      [
        5.4,
        3
      ],
      [
        3,
        2.1
      ]
    ]
  ],
  "crs": {
    "properties": {
      "name": "foo"
    },
    "type": "name"
  },
  "type": "Polygon"
}

我写了一个小的python可执行文件,将输出的json字符串解码成python对象,然后做一些事情:

import collections
import json
import sys
import logging

if __name__ == '__main__':

    try:
        geoJsonStr = str(sys.argv[1:])
        print geoJsonStr ## This for some reason only prints an empty slice '[]'
        data = json.loads(geoJsonStr)
        coordinates = data['coordinates'] ## TypeError: list indices must be integers, not str
        ## Do things here

    except ValueError as e:
        logging.error(e.message)
        exit(1)

我尝试这样称呼它:

jq '.geometry' geoJson.json | myPythonProgram

但是,如上面的代码 sn-p 中所述,我遇到了一些 python 错误。我认为这是我将jq 输出传递到我的python 可执行文件的方式。不知何故,整个 json 字符串没有作为argv 参数被拾取。

我的第一个错误是print GeoJsonStrargv[1:] 打印出一个空的[] 切片。所以我可能错误地将 json 字符串传递到 python 脚本中。随后的错误是:

coordinates = data['coordinates']

TypeError: list indices must be integers, not str

这可能或多或少是因为没有要解码的东西。

【问题讨论】:

标签: python json linux


【解决方案1】:

当您使用管道向程序发送数据时,您可以通过标准输入访问数据,而不是作为 argv 中的参数。

例如,假设您有以下程序:

foo.py:

import sys
data = sys.stdin.read()
print "I got", len(data), "characters!"

将一些数据输入其中会得到如下输出:

$ echo "foobar" | python foo.py
I got 6 characters!

请注意,在此示例中,对 python 的调用包含一个与输入完全分离的参数 (foo.py)。

在您的特定情况下,您可以像上面的示例一样直接读取标准输入,或者将sys.stdin 作为参数直接传递给json.load

import sys
...
obj = json.load(sys.stdin)
print obj

输出应该是这样的:

$ jq '.geometry' geoJson.json | python myPythonProgram.py
{u'crs': {u'type': u'name', u'properties': {u'name': u'foo'}}, u'type': u'Polygon', u'coordinates': [[[5, 2], [5.4, 3], [3, 2.1]]]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多