【问题标题】:JQ, convert CSV (parent child format) to JSON, another questionsJQ,将CSV(父子格式)转换为JSON,另一个问题
【发布时间】:2021-03-24 11:27:58
【问题描述】:

这是另一个帖子的继续: JQ, convert CSV (parent child format) to JSON

您好,很抱歉再次询问。我试图获得以下格式,但没有成功。非常感谢您的一些建议。我附上一张图片来展示它在层次结构视图中的样子a picture to show in a hierarchy way,也许它更容易。希望有可能吗?

*** CSV 文件 *****

id,parent_id,大小 主题,空,1 分析,主题,1 集群,分析,1 凝聚集群,集群,1 合并边缘,集群,2 动画,主题,1 缓动,动画,3 插值,动画,1 ArrayInterpolator,interpolate,4 矩形插值器,插值,5 补间,动画,6

这是我尝试实现的 JSON 文件。如果是父母(下有孩子),只显示身份证。如果是孩子,则显示 ID 和 Size。

**** JSON 文件 ****

{ "ID": "主题", “孩子们”: [{ “ID”:“分析”, “孩子们”: [{ “ID”:“集群”, “孩子们”: [{ "ID": "Aggl,ome,rativeCluster", “大小”:1 }, { "ID": "合并边缘", “大小”:2 }] }] }, { “ID”:“动画”, “孩子们”: [{ "ID": "缓动", “尺寸”:3 }, { “ID”:“插值”, “孩子们”: [{ "ID": "ArrayInterpolator", “大小”:4 }, { "ID": "矩形插值器", “大小”:5 }] }, { “ID”:“补间”, “尺寸”:6 }] }] }

【问题讨论】:

  • 嗨,李,理想情况下,如果您想继续这条路,您应该从后端获取 XML 格式的数据以获取 CSV 相关数据,这有利于将其转换为 XML,然后将其转换为 json 很容易。请查看此解决方案stackoverflow.com/questions/47940264/…

标签: json csv parent-child jq transitive-closure


【解决方案1】:

递归填写孩子的详细信息最容易 使用递归函数完成——这里是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)

【讨论】:

  • 非常感谢您的快速答复。非常令人印象深刻。我去看看数据。
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2019-05-14
  • 2022-01-01
  • 2015-06-22
  • 1970-01-01
相关资源
最近更新 更多