JQ,将CSV(父子格式)转换为JSON [英] JQ, convert CSV (parent child format) to JSON

查看:58
本文介绍了JQ,将CSV(父子格式)转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件(父子格式).是否可以通过使用JQ转换为JSON格式?

I have a CSV file (parent child format). Is it possible to convert to JSON format by using JQ ?

CSV文件 <pre>


id  parent_id   text
1   NULL        engine
2   1           exhaust
3   1           cooling
4   3           cooling fan
5   3           water pump
6   NULL        frame
7   6           wheels
8   6           brakes
9   8           brake calipers
10  6           cables
</Pre>

JSON文件 <Pre>


[
{
"id": "1",
"text": "engine",
"children": [
{
"id": "2",
"text": "exhaust",
"children": []
},
{
"id": "3",
"text": "cooling",
"children": [
{
"id": "4",
"text": "cooling fan",
"children": []
},
{
"id": "5",
"text": "water pump",
"children": []
}
]
}
]
},
{
"id": "6",
"text": "frame",
"children": [
{
"id": "7",
"text": "wheels",
"children": []
},
{
"id": "8",
"text": "brakes",
"children": [
{
"id": "9",
"text": "brake calipers",
"children": []
}
]
},
{
"id": "10",
"text": "cables",
"children": []
}
]
}
]
</Pre>

推荐答案

以下内容为完整解决上述问题提供了基础.代替 提供有关孩子的冗余详细信息,它仅提供他们的ID.如果您确实需要冗余,则只需再增加一个后处理步骤,这很简单.

The following provides the basis for a complete solution to the stated problem. Instead of providing the redundant details about the children, it just provides their ids. If you really need the redundancy, then simply add one more post-processing step, which is trivial to do.

此处的解决方案基于儿童"字典的构建.

The solution here is based on the construction of a dictionary of "children".

沿线:

jq -R -f program.jq data.csv

程序

def obj($headers):
  . as $in
  | reduce range(0; $headers|length) as $i ({}; 
      .[$headers[$i]] = $in[$i]);

split(",") as $headers
| [ inputs
    | split(",")
    | map_values(if . == "NULL" then null else . end)
    | obj($headers) ]
| (reduce .[] as $row ({};
      if $row.parent_id
      then .[$row.parent_id] += [$row.id]
      else . end ) ) as $children
| map( del(.parent_id) | .children = ($children[.id] // []) )

输出

使用给定的输入,输出开始如下:

Output

With the given input, the output begins as follows:

[
  {
    "id": "1",
    "text": "engine",
    "children": [
      "2",
      "3"
    ]
  },
  {
    "id": "2",
    "text": "exhaust",
    "children": []
  },

这篇关于JQ,将CSV(父子格式)转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆