发布于 1年前

nodejs写入json文件--引入fs,是实体写入的

book.json:

[

{"name":"book1","category":"1","quantity":"27","allowlend":"1"},

{"name":"book2","category":"2","quantity":"27","allowlend":"1"},

{"name":"book3","category":"3","quantity":"27","allowlend":"1"},

{"name":"book4","category":"4","quantity":"27","allowlend":"1"},

{"name":"book5","category":"5","quantity":"27","allowlend":"1"}

]

json.js --这个是用来运行的

var fs=require('fs');

fs.readFile('json/book.json',function(err,data){ //读取文件

if(err)

throw err;

var jsonObj=JSON.parse(data); //转换成json格式

console.log(jsonObj)

var space=' ';

var newLine=' . ';

var chunks=[];

var length=0;

for(var i=0,size=jsonObj.length;i<size;i++){

var record=jsonObj[i];

var name=record['name'];

var category=record['category'];

var quantity=record['quantity'];

var value=name+space+category+space+quantity+newLine;

var buffer=new Buffer(value);

chunks.push(buffer);

length+=buffer.length;

}

console.log(jsonObj)

console.log(26,chunks)

var resultBuffer=new Buffer(length);

for(var i=0,size=chunks.length,pos=0;i<size;i++){

chunks[i].copy(resultBuffer,pos);

pos+=chunks[i].length;

}

console.log(31,resultBuffer)

resultBuffer="{a:100,b'直接写入文件'}"

fs.writeFile('json/result.json',resultBuffer,function(err){

if(err) throw err;

console.log('write JSON into JSON');

});

});

执行下面的命令,

// node json/json.js

会在result.json中输入被改造过后的内容,--而且文件是可以随意写入的,字符串

©2020 edoou.com   京ICP备16001874号-3