如何将多行JSON对象管道化到单独的python调用中

2024-06-16 12:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道将stdin管道连接到shell中的下游流程的基础知识,只要每一条线都被单独处理,或者作为一个单独的输入,我就可以让我的管道正常工作。在

但是当我想读4行stdin,做一些处理,再读6行,然后做同样的事情时,我对管道的理解有限就成了一个问题。在

例如,在下面的管道中,每个curl调用都会生成一个未知数量的输出行,这些行组成一个JSONObject:

cat geocodes.txt \
  | xargs  -I% -n 1 curl -s 'http://maps.googleapis.com/maps/api/geocode/json?latlng='%'&sensor=true' \
  | python -c "import json,sys;obj=json.load(sys.stdin);print obj['results'][0]['address_components'][3]['short_name'];"

如何在每次python调用中只使用一个JSONObject?注意,实际上我在Python方面的经验微不足道。实际上,我对Node.js有更多的经验(使用它会更好吗节点.js处理JSON curl输出?)在

在地理代码.txt大概是:

^{pr2}$

编辑 我有一种讨厌的感觉,答案是你需要逐行阅读,并在解析之前检查你是否有一个完整的对象。有没有一个功能可以帮我完成这项艰巨的工作?在


Tags: txtjsonobj管道stdinsysjs经验
3条回答

你不需要python或者节点.js. jq是专门为json过滤设计的UNIX样式:

sudo apt-get install jq

然后:

^{pr2}$

或者,如果要对所有JPG文件执行此操作:

find -iname "**jpg" \
  | xargs -n 1 -d'\n' exiftool -q -n -p '$GPSLatitude,$GPSLongitude' 
  | xargs  -I% curl -s 'http://maps.googleapis.com/maps/api/geocode/json?latlng='%'&sensor=true'  
  | jq  unbuffered  '.results[0].formatted_address'

我相信这种方法可以达到你想要的效果。首先,将python脚本保存在一个文件中,例如my_script.py。然后执行以下操作:

cat geocodes.txt \
  | xargs  -I% sh -c "curl -s 'http://maps.googleapis.com/maps/api/geocode/json?latlng='%'&sensor=true' | python my_script.py"

我的_脚本.py是:

^{pr2}$

输出:

Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff

我承认这有点老套。在


原始答案

我不是bash向导,所以我的本能就是简单地用Python做任何事情。下面的脚本将在Python 3中演示这种方法:

import urllib.request as request
import urllib.parse as parse
import json

serviceurl = "http://maps.googleapis.com/maps/api/geocode/json?"

with open("geocodes.txt") as f:
    for line in f:
        url = (serviceurl +
               parse.urlencode({'latlng':line, 'sensor':'true'}))
        with request.urlopen(url) as response:
            bytes_data = response.read()
        obj = json.loads(bytes_data.decode('utf-8'))
        print(obj['results'][0]['address_components'][3]['short_name'])

输出:

Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff
Cardiff

看看:

http://trentm.com/json/#FEATURE-Grouping

Grouping can be helpful for "one JSON object per line" formats or for things such as:

$ cat *.json | json -g ...

要安装:

^{pr2}$

我自己还没有尝试过,所以无法验证它是否有效,但它可能是您想做的事情所缺少的链接(Group JSON)

相关问题 更多 >