我想解析输出的linux jq
调用python脚本,将解码输出jq
json str并做它的事情。解析输入argv json字符串
我jq
通话jq '.geometry' myJson.json
的输出是这样的:
{
"coordinates": [
[
[
5,
2
],
[
5.4,
3
],
[
3,
2.1
]
]
],
"crs": {
"properties": {
"name": "foo"
},
"type": "name"
},
"type": "Polygon"
}
我已经写了一个小蟒蛇的可执行文件,解码输出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:]
打印出一个空的[]
切片。所以我可能会错误地将json字符串传递给python脚本。随后的错误是:
coordinates = data['coordinates']
TypeError: list indices must be integers, not str
这可能是或多或少因为没有什么解码。
如果您'出错了,你需要把它们包含在这里。 – Carcigenicate
可能与[如何在bash中创建一个python脚本“pipeable”]相同?(https://stackoverflow.com/questions/4429966/how-to-make-a-python-script-pipeable-in- bash)也许这个问题会有所帮助 –