JQ - 如何将带标题的 CSV 转换为带嵌套字典的 JSON 数组

发布于 2025-01-10 01:14:22 字数 439 浏览 1 评论 0原文

我得到了以下 CSV 示例

key1,key2,key3,key4,key5
val1,val2,val3,val4,val5

寻找如何将上述结构转换为以下 JSON 结构的提示

[
{
"event": "bleep",
"sourcetype": "rats",
"fields":  {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
 }
},
{
"event": "bleep",
"sourcetype": "rats",
"fields":  {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
 }
}
]

提前致谢!

I got the following CSV sample

key1,key2,key3,key4,key5
val1,val2,val3,val4,val5

Looking for tips how to convert the above structure into the following JSON structure

[
{
"event": "bleep",
"sourcetype": "rats",
"fields":  {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
 }
},
{
"event": "bleep",
"sourcetype": "rats",
"fields":  {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
 }
}
]

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撕心裂肺的伤痛 2025-01-17 01:14:22

使用 -R 将输入读取为原始文本

jq -R '
  (. / ",") as $keys
  | [ inputs / "," | [$keys, .]
    | reduce transpose[] as $i (
        {event: "bleep", sourcetype: "rats"}; .fields[$i[0]] = $i[1])
      ]
' input.csv

演示

Use -R to read the input as raw text

jq -R '
  (. / ",") as $keys
  | [ inputs / "," | [$keys, .]
    | reduce transpose[] as $i (
        {event: "bleep", sourcetype: "rats"}; .fields[$i[0]] = $i[1])
      ]
' input.csv

Demo

在巴黎塔顶看东京樱花 2025-01-17 01:14:22

Alasql lib 可以从服务器加载数据文件,解析它并将结果放入 JSON 对象数组。

所以,这是给你的一些例子:

<script src="alasql.min.js"></script>
<script>
        alasql('SELECT * FROM CSV("FileName.csv",{headers:true})',[],function(res){
        var dataResult = {items:res};
        });
</script>

Alasql lib can load the data file from server, parse it and put the result to array of JSON objects.

So, this is some example for you:

<script src="alasql.min.js"></script>
<script>
        alasql('SELECT * FROM CSV("FileName.csv",{headers:true})',[],function(res){
        var dataResult = {items:res};
        });
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文