将CSV数组转换为具有节点和边缘的JSON文件的任何已知方法



简要示例

CSV 文件 :

name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

理论对应JSON文件:

{
  "comment": "example code",
  "nodes": [
    {
      "name": John,
      "source" : A
    },
    {
      "name": Emma ,
      "source" : B
    },
    {
      "name": Mike , 
      "source" : C
    }
  ],
  "links": [
    {
      "source": B,
      "target": A
    },
    {
      "source": C,
      "target": A
    }
  ]
}

生成的图形概念:

B  -> A  <-  C

上面的 JSON 文件不是绝对的。它可以具有各种架构。上面的例子是非常基本的。

我希望有一个软件或库可以轻松地将CSV数组转换为JSON文件或类似的东西。

有很多CSV文件,我想把它们变成JavaScript图形,但首先我需要一个数据结构良好的JSON输入文件。我想自动化 JSON 文件构建。

下面是一个使用 csvtojson 的示例。

const csv = require('csvtojson');
const csvFilePath = 'test.csv';
var data = [];
csv().fromFile(csvFilePath)
    .on('json', (jsonObj) => {
        data.push(jsonObj);
    })
    .on('done', (error) => {
        if (error) {
            console.error(error);
        } else {
            formatData(data);
        }
    });
function formatData(data) {
    var formatted = {
        comment: "hello",
        nodes: [],
        links: []
    };
    data.forEach(function(r){
        //check for your empty or 'None' fields here
        if(r.name && r.source){
            formatted.nodes.push({ name: r.name, source: r.source });
        }
        if (r.source && r.target) {
            formatted.links.push({ source: r.source, target: r.target });
        }
    });
    //do something with the finished product
    console.log(formatted);
}

这是一个使用 jq 的解决方案

如果文件filter.jq包含

[
  split("n")                                                    # split string into lines
| [.[0]    | split(",")[] | gsub("[[:space:]]+";"")] as $headers # split header
| (.[1:][] | split(","))                                         # split data rows
| select(length>0)                                               # get rid of empty lines
| [   [ $headers, map(gsub("[[:space:]]+";"")) ]                 # 
    | transpose[]                                                # assemble objects
    | {key:.[0], value:.[1]}                                     # from keys and values
  ] | from_entries                                               #
]
| {
    "comment":"example code",                                    # convert objects
    "nodes": map({name,source}),                                 # to requested format
    "links": map(select(.target!="None")|{source,target})        #
  }

并且data包含

name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

然后命令

jq -M -R -s -r -f filter.jq data    

将产生

{
  "comment": "example code",
  "nodes": [
    {
      "name": "John",
      "source": "A"
    },
    {
      "name": "Emma",
      "source": "B"
    },
    {
      "name": "Mike",
      "source": "C"
    }
  ],
  "links": [
    {
      "source": "B",
      "target": "A"
    },
    {
      "source": "C",
      "target": "A"
    }
  ]
}

最新更新