1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jsonをcsv(カンマ区切り、項目行あり)に変換する(構文破壊に対応)

Last updated at Posted at 2020-07-31

以下の記事にあるJSON変換用関数、すごくわかりやすくて重宝しているのですが、
文字列をダブルクオーテーションで囲んでないので、
「あいうえお"」や「あい,うえお」のような、構文破壊系の文言が来ると死にます。

ので、見出し行以外を全てダブルクォーテーションで囲んでカンマによる構文破壊を防ぎ、
ダブルクォーテーション一つだけの文字列は二つにすることで、そちらの構文破壊も防ぐようにします。

おまけで、見出し行を出力するかどうかを選択できるようにしました

実装

/**
 * Convert json to csv
 * Supports syntactic destruction
 *
 * @params array-object records
 * @params boolean isHeaderDraw [default true]
 * @return string
 * @link https://qiita.com/_shimizu/items/38e6d75afcacec25eb7e
 * @link https://qiita.com/qwe001/items/60f6cb264110490d7d90
 */
function json2csv(records, isHeaderDraw)
{
  var isHeaderDraw = isHeaderDraw !== undefined && isHeaderDraw === false ? false : true;

  if(! records || records.length === 0){
    return "";
  }

  var header = Object.keys(records[0]).join(',') + "\n";

  var body = records.map(record => {
    record = Object.keys(record).map(key => {
      var field = record[key];
      if (field) {
        field = field.replace(/\"/g, "\"\"");
        //field = field.replace(/\r?\n/g, " "); // 改行を無効にしたい場合
      }
      return field;
    }).join("\",\"");

    return "\"" + record + "\"";
  }).join("\n");

  return isHeaderDraw ? header + body : body;
}

使い方

var a = [
    {id:1, name:"test", address:"tokyo"},
    {id:2, name:"hoge", address:"構文破壊1\""},
    {id:3, name:"hello", address:"構文,破壊2"},
    {id:4, name:"world", address:"saitama"}
];

json2csv(a);

//output
id,name,address
"1","test","tokyo"
"2","hoge","構文破壊1"""
"3","hello","構文,破壊2"
"4","world","saitama"

// 見出し行が要らへんとき
json2csv(a, false);

//output
"1","test","tokyo"
"2","hoge","構文破壊1"""
"3","hello","構文,破壊2"
"4","world","saitama"

バグなどあったら教えてくれると助かります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?