[英]JQ, convert CSV (parent child format) to JSON, another questions
这是另一个帖子的继续: JQ,将 CSV(父子格式)转换为 JSON
您好,不好意思再问。 我试图获得以下格式,但没有成功。 非常感谢您的一些建议。 我附上一张图片来显示它在层次视图中的样子,一张图片以层次方式显示,也许更容易。 希望有可能吗?
*** CSV 文件 *****
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
这是我试图实现的 JSON 文件。 如果是父母(下有孩子),只显示身份证。 如果是孩子,则显示 ID 和 Size。
**** 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 }] }] }
使用递归 function 可以最容易地递归地填写有关儿童的详细信息——这里是closure/2
,它的编写是为了非常有效。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.