2017-05-11 16 views
0

とJSONファイルにCSV配列を変換する方法の簡単な例任意の既知ノードおよびエッジ

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ファイルやその行に沿って簡単に変換できるソフトウェアまたはライブラリが必要です。

私はJavaScriptグラフに変換するたくさんのCSVファイルがありますが、まずデータが整理されたJSON入力ファイルが必要です。私はJSONファイルの構築を自動化したいと思います。

答えて

0

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); 
} 
0

ファイル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

を使用したソリューションであります10

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" 
    } 
    ] 
} 
が生成されます
関連する問題