【1:读取json写入txt文件】
json文件
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"}
]
js文件
var fs = require('fs'); //fs是读取文件的模板工具
fs.readFile('book.json',function(err,data){//读取同目录下的book.json文件
if(err){throw err;}
var jsonObj = JSON.parse(data);//获取json文件对象
var space = ' ';
var newLine = ' . ';
var chunks = [];
var length = 0;
for(var i=0 ; i
【2:读取json写入redis文件/以实际项目为例】
【1:json文件(test.json)】
{
"1":[
{"coordinateX": "43.74", "coordinateY": "2.41"},
{"coordinateX": "43.74", "coordinateY": "2.39"},
{"coordinateX": "43.74", "coordinateY": "2.41"},
{"coordinateX": "43.74", "coordinateY": "2.39"}
],
"2":[
{"coordinateX": "43.74", "coordinateY": "2.41"},
{"coordinateX": "43.74", "coordinateY": "2.39"},
{"coordinateX": "43.74", "coordinateY": "2.39"}
],
"3":[
{"coordinateX": "43.74", "coordinateY": "2.39"},
{"coordinateX": "43.74", "coordinateY": "2.41"},
{"coordinateX": "43.74", "coordinateY": "3.00"}
]
}
【2:redis模板链接 /redis.js】
var redis = require("redis").createClient({
host: 'localhost',
port: 6379,
detect_buffers: true,
db: 0, //password: 'a8fY6gkg04jGc9d3LbvY',
no_ready_check: true,
retry_strategy: function (options) {
return Math.max(1000);
}
});
module.exports = redis;
【3:读取JSON并存入redis的工具类/readJson.js】
var fs = require('fs');
var uti = {};
uti.readJson = function (fn) {
fs.readFile('../JsonFile/test.json', function (err, data) {
var jsonObj;
if (err) { throw err; }
jsonObj = JSON.parse(data);
fn({obj:jsonObj}) //将读取的jsonOBJ对象返回
});
};
module.exports = uti;
【4:controller层调用解析json对象并存入redis】
readJson.readJson(function (date) {
for (var key in date.obj) {
var val = date.obj[key];
//console.log("--------" + key + " : " + val.length);
for (var i = 0; i < val.length; i++) {
var posArr = val[i];
var coordinateX = posArr.coordinateX;
var coordinateY = posArr.coordinateY;
var pos = coordinateX + "_" + coordinateY;
arr.push(pos);
}
//存入
redis.set("string key", "Hello World", function (err, reply) {
console.log(reply.toString());
});
//取出
redis.get(key, function (err, reply) {
console.log(reply.toString());
});
}
});