JQ,将CSV(父子格式)转换为JSON,另一个问题
这是另一篇文章的继续: 嗨,抱歉再问一次。我试图获得以下格式,但没有成功。非常感谢你的建议。我附加了一张图片来显示它在层次视图中的样子,也许这更容易。希望这是可能的 ***CSV文件***** id、父项id、大小 主语,空,1 分析学,学科,1 群集,分析,1 凝聚性集群,集群,1 合并边缘,群集,2 制作动画,主题,1 放松,动画,3 插值,设置动画,1 ArrayInterpolator,插值,4 矩形插值器,插值,5 特温,动画,6 这是我试图实现的JSON文件。如果是父项(下有子项),则仅显示ID。如果是子项,则显示ID和大小 ****JSON文件**** { “ID”:“主体”, “儿童”:[{ “ID”:“分析”, “儿童”:[{ “ID”:“集群”, “儿童”:[{ “ID”:“AGG、ome、rativeCluster”, “尺寸”:1 }, { “ID”:“MergeEdge”, “尺寸”:2 }] }] }, { “ID”:“动画”, “儿童”:[{ “ID”:“放松”, “尺寸”:3 }, { “ID”:“插入”, “儿童”:[{ “ID”:“ArrayInterpolator”, “尺寸”:4 }, { “ID”:“矩形插值器”, “尺寸”:5 }] }, { “ID”:“Tween”, “尺寸”:6 }] }] }JQ,将CSV(父子格式)转换为JSON,另一个问题,json,csv,parent-child,jq,transitive-closure,Json,Csv,Parent Child,Jq,Transitive Closure,这是另一篇文章的继续: 嗨,抱歉再问一次。我试图获得以下格式,但没有成功。非常感谢你的建议。我附加了一张图片来显示它在层次视图中的样子,也许这更容易。希望这是可能的 ***CSV文件***** id、父项id、大小 主语,空,1 分析学,学科,1 群集,分析,1 凝聚性集群,集群,1 合并边缘,群集,2 制作动画,主题,1 放松,动画,3 插值,设置动画,1 ArrayInterpolator,插值,4 矩形插值器,插值,5 特温,动画,6 这是我试图实现的JSON文件。如果是父项(下有子项)
递归地填写关于孩子的详细信息是最容易做到的 使用递归函数完成——此处为
closure/2
,编写该函数是为了提高效率
id,parent_id,size
Subject,Null,1
analytics,Subject,1
cluster,analytics,1
AgglomerativeCluster,cluster,1
MergeEdge,cluster,2
animate,Subject,1
Easing,animate,3
interpolate,animate,1
ArrayInterpolator,interpolate,4
RectangleInterpolator,interpolate,5
Tween,animate,6
Hi Lee,理想情况下,您应该从CSV相关数据的后端获取XML格式的数据。如果您想继续,将其转换为XML是有益的,那么将其转换为json是很容易的。请查看此解决方案,非常感谢您的快速回答。非常令人印象深刻。我来看看数据。 { "ID": "Subject", "children": [{ "ID": "analytics", "children": [{ "ID": "cluster", "children": [{ "ID": "Aggl,ome,rativeCluster", "size": 1 }, { "ID": "MergeEdge", "size": 2 }] }] }, { "ID": "animate", "children": [{ "ID": "Easing", "size": 3 }, { "ID": "interpolate", "children": [{ "ID": "ArrayInterpolator", "size": 4 }, { "ID": "RectangleInterpolator", "size": 5 }] }, { "ID": "Tween", "size": 6 }] }] }
def obj($headers):
. as $in
| reduce range(0; $headers|length) as $i ({};
.[$headers[$i]] = $in[$i]);
# input: either the id of an individual or
# an object representing an individual;
# output: the same individual but with .children and recursively
# their children as an array of objects
def closure($dictionary; $children):
def c:
if type == "string" then $dictionary[.] | c
elif type=="object"
then if has("children")
then if (.children|length)>0 then .children = map(c) else . end
elif $children[.id] then .children = ($children[.id] | map(c))
else . end
else . end;
c;
split(",") as $headers
| [ inputs
| split(",")
| map_values(if . == "Null" then null else . end)
| obj($headers) ]
| INDEX(.[]; .id) as $ids # a dictionary mapping id => object
| (reduce .[] as $row ({};
if $row.parent_id
then .[$row.parent_id] += [$row.id]
else . end ) ) as $children # string => [ string ]
| map(closure($ids; $children) )
# tidy up:
| walk(if type=="object"
then if .children and (.children|length) > 0
then del(.size)
else . end
| del(.parent_id)
else . end)