【发布时间】:2017-08-06 20:39:12
【问题描述】:
我有
{"a":1} {"b":2}
我想用jq来获取
{"a": 1, "b":2}
jq --slurp add myfile 效果很好。但是,我想将它与jq.py 一起使用,它没有slurp 模式。 jq 是否有办法在不使用 --slurp 的情况下对任意对象序列(具有不同的键)执行此操作?
【问题讨论】:
我有
{"a":1} {"b":2}
我想用jq来获取
{"a": 1, "b":2}
jq --slurp add myfile 效果很好。但是,我想将它与jq.py 一起使用,它没有slurp 模式。 jq 是否有办法在不使用 --slurp 的情况下对任意对象序列(具有不同的键)执行此操作?
【问题讨论】:
比使用 [inputs] 对内存的要求更低的是:
reduce inputs as $in ({}; . + $in)
以上假设 -n 命令行选项有效。如果 py.jq 无法做到这一点,则应使用以下过滤器:
reduce inputs as $in (.; . + $in)
附言 如果 py.jq 的作者知道了命令行选项的问题,也许会愿意解决它?
【讨论】:
如果您使用 python 读取 myfile,splitstream 模块 described here 可能是您想要的。这是一个使用jq.py 的测试示例(test.py)。
import splitstream
from jq import jq
def slurp(filename):
with open(filename) as f:
for s in splitstream.splitfile(f, format="json"):
yield s
obj = {}
for jstr in slurp('myfile'):
obj = jq("[%s, .] | add" % obj).transform(text=jstr, text_output=True)
print obj
这是一个示例运行
$ cat myfile
{"a":1}
{"b":2}
$ python test.py
{"a":1,"b":2}
虽然这似乎可以满足您使用jq.py 的要求,但我认为这不是一个好的解决方案,因为在 python 和 jq 之间共享状态既笨拙又低效。
更好的方法可能是将 jq 用作子进程。这是一个例子(test2.py):
import json
import sh
cmd = sh.jq('-M', '-s', 'add', 'myfile')
obj = json.loads( cmd.stdout )
print json.dumps(obj, indent=2)
示例运行:
$ python test2.py
{
"a": 1,
"b": 2
}
【讨论】:
这会产生所需的输出。
jq -nc '[inputs] | add'
不过,我不能说它是否适用于 jq.py。
【讨论】: