【发布时间】:2018-03-28 10:09:14
【问题描述】:
在一个大的 json 文件中,我想从嵌套列表中删除一些元素,但保留文档的整体结构。
我的示例输入它(但真实的足够大,可以要求流式传输)。
{
"keep_untouched": {
"keep_this": [
"this",
"list"
]
},
"filter_this":
[
{"keep" : "true"},
{
"keep": "true",
"extra": "keeper"
} ,
{
"keep": "false",
"extra": "non-keeper"
}
]
}
所需的输出只删除了“filter_this”块的一个元素:
{
"keep_untouched": {
"keep_this": [
"this",
"list"
]
},
"filter_this":
[
{"keep" : "true"},
{
"keep": "true",
"extra": "keeper"
} ,
]
}
处理此类情况的标准方法似乎是使用“truncate_stream”重构流对象,然后以通常的 jq 方式过滤这些对象。具体来说,命令:
jq -nc --stream 'fromstream(1|truncate_stream(inputs))'
允许访问对象流:
{"keep_this":["this","list"]}
[{"keep":"true"},{"keep":"true","extra":"keeper"},
{"keep":"false","extra":"non-keeper"}]
此时很容易过滤出所需的对象。但是,这会从其父对象的上下文中剥离结果,这不是我想要的。
看流式结构:
[["keep_untouched","keep_this",0],"this"]
[["keep_untouched","keep_this",1],"list"]
[["keep_untouched","keep_this",1]]
[["keep_untouched","keep_this"]]
[["filter_this",0,"keep"],"true"]
[["filter_this",0,"keep"]]
[["filter_this",1,"keep"],"true"]
[["filter_this",1,"extra"],"keeper"]
[["filter_this",1,"extra"]]
[["filter_this",2,"keep"],"false"]
[["filter_this",2,"extra"],"non-keeper"]
[["filter_this",2,"extra"]]
[["filter_this",2]]
[["filter_this"]]
似乎我需要选择所有“filter_this”行,仅截断这些行(使用“truncate_stream”),将这些行重建为对象(使用“from_stream”),过滤它们,然后将对象转回流中数据格式(使用“tostream”)加入“保持不变”行的流,这些行仍然是流格式。那时,可以重新构建整个 json。如果这是正确的方法——这对我来说似乎过于复杂——我该怎么做?或者,还有更好的方法?
【问题讨论】:
-
最好的方法是尽可能避免使用流解析器。您是否有足够的 RAM 来在您的数据上运行类似“jq length”之类的东西?
标签: json bigdata jq stream-processing