24
21

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.

JavascriptでJSONファイルを読み込み/書き込み

Last updated at Posted at 2020-05-04

インストール

sudo apt-get install nodejs npm    # nodejsをインストール
sudo apt-get install jq            # jqをインストール

jsonファイルを作成する

writejson.js
var fs = require('fs');
var masterData = [];

var data = {
    Name: 'taro',
    age: '1',
    weight: 3.0,
};
var data2 = {
    Name: 'jiro',
    age: '0.5',
    weight: 2.0,
};

masterData.push(data)
masterData.push(data2)
let masterData2 = JSON.stringify({MyDog: masterData}, null, ' ')
fs.writeFileSync('output.json', masterData2);

実行

$ node writejson.js
$ cat output.json| jq
{
  "MyDog": [
    {
      "Name": "taro",
      "age": "1",
      "weight": 3
    },
    {
      "Name": "jiro",
      "age": "0.5",
      "weight": 2
    }
  ]
}

jsonファイルを読み込む

readjson.js
const fs = require('fs');

const jsonObject = JSON.parse(fs.readFileSync('./output.json', 'utf8'));
const result = {};

jsonObject.MyDog.forEach((obj) => {
	result[obj.date] = obj;
	console.log(obj.Name, obj.age ,obj.weight )
});

実行

$ node readjson.js
taro 1 3
jiro 0.5 2

jsonファイルを読み込んで書き出す

readandwritejson.js
const fs = require('fs');

const jsonObject = JSON.parse(fs.readFileSync('./output.json', 'utf8'));
const result = {};
var masterData = [];

jsonObject.MyDog.forEach((obj) => {
	result[obj.date] = obj;
	console.log(obj.Name, obj.age ,obj.weight )
	var data = {
	    Name: obj.Name,
	    age: obj.age,
	    weight: obj.weight,
	};
	masterData.push(data)
});

let masterData2 = JSON.stringify({MyDog: masterData}, null, ' ')
fs.writeFileSync('output2.json', masterData2);

実行

$ node readandwritejson.js
taro 1 3
jiro 0.5 2
$ cat output2.json| jq
{
  "MyDog": [
    {
      "Name": "taro",
      "age": "1",
      "weight": 3
    },
    {
      "Name": "jiro",
      "age": "0.5",
      "weight": 2
    }
  ]
}

参考

JSON.stringify()
Node.jsでJSONを読み込んで加工して書き出す
Node.js でファイルを保存する方法
JavaScriptでJSONファイルを読み込む方法
コマンドラインでJSONファイルを整形して表示させる
【Python】JSONファイルの読み込み書き込み
JSON入門

24
21
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
24
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?