LoginSignup
1
0

More than 1 year has passed since last update.

Typescriptでcsvtojsonを使い2つのcsv文字列をjsonに変換する

Last updated at Posted at 2021-07-25

Typescriptで2つのcsv形式の文字列をいい感じにjsonに変換したいのだが
https://www.npmjs.com/package/csvtojson
とかを見てもいい感じの例を見つけられなかったので記載します。

以下のような2つのcsv形式の文字列があった場合にjsonに変換したい場合

文字列A

hoge,fuga

文字列B

1,2

変換後の文字列

{ hoge: '1', fuga: '2' }

やり方

もちろんやり方はいくつもあると思うのですが以下で実現できました

convert_csv_to_json.ts
const csv = require('csvtojson')

const n = "hoge,fuga"
const s = "1,2"
const csvStr = n + "\n" + s

csv({flatKeys:true})
.fromString(csvStr)
.subscribe((jsonObj:string)=>{
        console.log(jsonObj)
});

また関数から呼び出したい場合は以下でできました。
https://stackoverflow.com/questions/50990456/node-js-csvtojson-return-result-outside-of-function
よりcsvtojsonはPromise objectを返すので値の取り出し方もPromise内で行います

convert_csv_to_json.ts
const csv = require('csvtojson')

const n = "hoge,fuga"
const s = "1,2"
const csvStr = n + "\n" + s

function fugafunc(csvStr:String):Promise<String>{
  return csv().fromString(csvStr);
}

const result = fugafunc(csvStr)
result.then((data: String) => {console.log(data) })


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0