1
1

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 1 year has passed since last update.

Node.jsで扱うよく扱うデータ形式の基礎知識

Last updated at Posted at 2020-09-11

##JSON
ご存知、JSON(JavaScript Object Notation)形式。
JSONオブジェクトは、標準ビルトインオブジェクトなので特別な準備なしで手軽に扱うことができる。

###サンプル

JSONの例
{
  "browsers": {
    "firefox": {
      "name": "Firefox",
      "pref_url": "about:config",
      "releases": {
        "1": {
          "release_date": "2004-11-09",
          "status": "retired",
          "engine": "Gecko",
          "engine_version": "1.7"
        }
      }
    }
  }
}

###使用方法
モジュールのインストールなどは不要。

// 文字列textをJSONとして解析し、JSオブジェクトに変換
const obj = JSON.pares(text)

// JSオブジェクトをJSON文字列に変換
const text = JSON.stringify(obj)

##JSON5
JSON5は、JSONのスーパーセット。JSONの制限の一部を緩和する。

JSON5の拡張

  • 末尾にコンマがあってもエラーにならない
  • 文字列を一重引用符で囲むことができる
  • 複数行の文字列を扱える(改行文字をエスケープする)
  • 単一行および複数行のコメントが使える
  • 空白文字を使用できる
    など

###サンプル

JSON5の例
{
  // comments
  unquoted: 'and you can quote me on that',
  singleQuotes: 'I can use "double quotes" here',
  lineBreaks: "Look, Mom! \
No \\n's!",
  hexadecimal: 0xdecaf,
  leadingDecimalPoint: .8675309, andTrailing: 8675309.,
  positiveSign: +1,
  trailingComma: 'in objects', andIn: ['arrays',],
  "backwardsCompatible": "with JSON",
}

###インストール

Node.jsの場合
npm install json5
ブラウザの場合
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>

###使用方法

const JSON5 = require('json5')

// 文字列textをJSON5として解析し、JSオブジェクトに変換
const obj = JSON5.pares(text)

// JSオブジェクトをJSON5文字列に変換
const text = JSON5.stringify(obj)

##CSON
CSON(CoffeeScript-Object-Notation)は、CoffeeScript記法を基にしたデータ形式。

###サンプル

CSONの例
{
  "greatDocumentaries": [
    "earthlings.com",
    "forksoverknives.com",
    "cowspiracy.com"
  ],
  "importantFacts": {
    "emissions": "Livestock and their byproducts account for at least 32,000 million tons of carbon dioxide (CO2) per year, or 51% of all worldwide greenhouse gas emissions.\nGoodland, R Anhang, J. “Livestock and Climate Change: What if the key actors in climate change were pigs, chickens and cows?”\nWorldWatch, November/December 2009. Worldwatch Institute, Washington, DC, USA. Pp. 10–19.\nhttp://www.worldwatch.org/node/6294",
    "landuse": "Livestock covers 45% of the earth’s total land.\nThornton, Phillip, Mario Herrero, and Polly Ericksen. “Livestock and Climate Change.” Livestock Exchange, no. 3 (2011).\nhttps://cgspace.cgiar.org/bitstream/handle/10568/10601/IssueBrief3.pdf",
    "burger": "One hamburger requires 660 gallons of water to produce – the equivalent of 2 months’ worth of showers.\nCatanese, Christina. “Virtual Water, Real Impacts.” Greenversations: Official Blog of the U.S. EPA. 2012.\nhttp://blog.epa.gov/healthywaters/2012/03/virtual-water-real-impacts-world-water-day-2012/\n“50 Ways to Save Your River.” Friends of the River.\nhttp://www.friendsoftheriver.org/site/PageServer?pagename=50ways",
    "milk": "1,000 gallons of water are required to produce 1 gallon of milk.\n“Water trivia facts.” United States Environmental Protection Agency.\nhttp://water.epa.gov/learn/kids/drinkingwater/water_trivia_facts.cfm#_edn11",
    "more": "http://cowspiracy.com/facts"
  }
}

###インストール

npm install cson

###使用方法

const CSON = require('cson')

// 文字列textをCSONとして解析し、JSオブジェクトに変換
const obj = CSON.pares(text)

// JSオブジェクトをCSON文字列に変換
const text = CSON.stringify(obj)

##HTML/XML/RSS
cheerioは、コアjQueryのサブセット。

###インストール

npm install cheerio

###使用方法

const cheerio = require('cheerio')
const $ = cheerio.load('<h2 class="title">Hello world</h2>')
 
$('h2.title').text('Hello there!')
$('h2').addClass('welcome')
 
$.html()
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>

##YAML
YAML(ヤムル、YAML Ain't a Markup Language)は、JSONのスーパーセットです。
設定ファイルによく使われています。

###サンプル

リスト
--- # お好みの映画、ブロック形式
- Casablanca
- Spellbound
- Notorious
--- # 買い物リスト、インライン形式、またはフロー形式
[milk, bread, eggs]
連想配列
 --- # ブロック
 name: John Smith
 age: 33
 --- # インライン
 {name: John Smith, age: 33}

###インストール

js-yamlのインストール
npm install js-yaml

###使用方法

YAMLの使用方法
const yaml = require('js-yaml')

const obj = yaml.safeLoad(txt)
for (var i in obj.items) {
  const it = obj.items[i]
  console.log(it.name, it.price)
}

##INI
INI(イニ)ファイルは、昔から設定ファイルによく使われています。

###サンプル

INIファイル
[section1]
name1=value1
name2=value2

[section2]
name3=value3

###インストール

iniのインストール
npm install ini

###使用方法

iniの使用方法
const ini = require('ini')

const obj = ini.parse(txt)

for (const name in obj) {
  const it = obj[name]
  console.log(name, it.price, it.color)
}

##CSV
RFC4180準拠のcomma-separated-valuesを使う。

###サンプル

"aaa","bbb","ccc"
zzz,yyy,xxx

###インストール

node.jsの場合
npm install comma-separated-values
ブラウザの場合
<script src="csv.min.js"></script>

###使用方法

const CSV = require('comma-separeted-values')

const csv = new CSV(txt, {header:fales)}
const records = csv.parse()

##Word/Excel/Powerpoint
officegenは、Microsoft Office 2007以降用のOffice Open XMLファイル(Word、Excel、Powerpoint)を、外部ツールなしで純粋なJavaScriptで作成します。

###インストール

npm install officegen

###使用方法

const officegen = require('officegen')
const fs = require('fs')
 
// Create an empty Excel object:
let xlsx = officegen('xlsx')
 
// Officegen calling this function after finishing to generate the xlsx document:
xlsx.on('finalize', function(written) {
  console.log(
    'Finish to create a Microsoft Excel document.'
  )
})
 
// Officegen calling this function to report errors:
xlsx.on('error', function(err) {
  console.log(err)
})
 
let sheet = xlsx.makeNewSheet()
sheet.name = 'Officegen Excel'
 
// Add data using setCell:
 
sheet.setCell('E7', 42)
sheet.setCell('I1', -3)
sheet.setCell('I2', 3.141592653589)
sheet.setCell('G102', 'Hello World!')
 
// The direct option - two-dimensional array:
 
sheet.data[0] = []
sheet.data[0][0] = 1
sheet.data[1] = []
sheet.data[1][3] = 'some'
sheet.data[1][4] = 'data'
sheet.data[1][5] = 'goes'
sheet.data[1][6] = 'here'
sheet.data[2] = []
sheet.data[2][5] = 'more text'
sheet.data[2][6] = 900
sheet.data[6] = []
sheet.data[6][2] = 1972
 
// Let's generate the Excel document into a file:
 
let out = fs.createWriteStream('example.xlsx')
 
out.on('error', function(err) {
  console.log(err)
})
 
// Async call to generate the output file:
xlsx.generate(out)

##PDF
html-pdfは、開発終了のPhantomJSを使っているので使用は避けたいけれども。

###インストール

html-pdfのインストール
npm install html-pdf

###使用方法

html-pdf使用方法
ar fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
 
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' }
});
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?