Python 解析输入argvjson字符串

Python 解析输入argvjson字符串,python,json,linux,Python,Json,Linux,我想将linuxjq调用的输出解析为一个python脚本,该脚本将解码输出jqjson str并对其进行处理 myjq调用jq'.geometry'myJson.json的输出如下: { "coordinates": [ [ [ 5, 2 ], [ 5.4, 3 ], [ 3, 2.1 ] ] ], "

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

my
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
然而,正如我在上面的代码片段中所指出的,我遇到了一些python错误。我认为这就是我将
jq
输出传递到python可执行文件的方式。不知何故,整个json字符串没有作为
argv
参数提取

我的第一个错误是
print GeoJsonStr
argv[1://code>打印出一个空的
[]
切片。因此,我可能错误地将json字符串传递到python脚本中。随后的错误是:

coordinates = data['coordinates']
TypeError:列表索引必须是整数,而不是str


这可能或多或少是因为没有可解码的内容。

当您使用管道向程序发送数据时,可以通过stdin访问数据,而不是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)

在您的特定情况下,您可以像上面的示例一样直接读取stdin,或者直接将
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]]]}

如果你有错误,你需要把它们包括在这里。可能问同样的问题,也许这个问题会有帮助