json是基于ECMAScript的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。可是要将json文件的数据转化为对象然后导入到数据库中怎么做?接下来我们就来给大家讲解一下。
使用到的工具
nodejs vscode
vscode : 轻量级的编辑器,支持多种格式的文件。 node.js: 简单的说 Node.js 就是运行在服务端的 JavaScript。
json格式文件:
//example for the json fire [ { "number": "001" , "name": "烟感" , "floor": "3" , "position": "3层南竖井" }, { "number": "002" , "name": "烟感" , "floor": "3" , "position": "3层南电梯厅" }, { "number": "003" , "name": "烟感" , "floor": "3" , "position": "3层东走廊" }, { "number": "004" , "name": "烟感" , "floor": "3" , "position": "3层东走廊" }, { "number": "005" , "name": "烟感" , "floor": "3" , "position": "3层东走廊" }, { "number": "006" , "name": "烟感" , "floor": "3" , "position": "3层东走廊" }, { "number": "007" , "name": "烟感" , "floor": "3" , "position": "3层北电梯厅" }, { "number": "008" , "name": "烟感" , "floor": "8" , "position": "8302房" }, { "number": "009" , "name": "烟感" , "floor": "3" , "position": "3层配电室" }, { "number": "010" , "name": "烟感" , "floor": "8" , "position": "8301房" }, { "number": "011" , "name": "烟感" , "floor": "8" , "position": "8303房" }, { "number": "012" , "name": "烟感" , "floor": "8" , "position": "8305房" }, { "number": "013" , "name": "烟感" , "floor": "8" , "position": "8307房" }, { "number": "014" , "name": "烟感" , "floor": "8" , "position": "8309房" }
上面json 文件的编辑我们可以使用vscode来进行编辑,简单为大家介绍一下文本编辑所使用到的快捷键:
ctrl+shirt+l: 选中文本中相同的属性;
ctrl+alt: 多行编辑;
shirt+end:光标移动到当前行末尾,可实现选中功能;
home: 回到当前行起始位置;
end : 回到当前行末尾位置;
编辑多行json文件使用vscode是比较省事的。
node.js上代码
// example for node.js fire //连接数据库 const mysql = require('mysql'); const connection = mysql.createConnection( { host: 'localhost' , user: 'root' , password: 'admin' , database: 'node' }); connection.connect(); const fs = require('fs'); const jsonFile = './sim.json'; //此处为你的json文件 const jsonObj = JSON.parse(fs.readFileSync(jsonFile)); const uuidv1 = require('uuid/v1'); console.log(uuidv1()); // test uuid (generated by timestamp) (async () => { for (let w of jsonObj.data) { try { let addSql = `INSERT INTO b_sim (uuid,sim,code,activation_date,expriation_date,remark,create_time) VALUES(?,?,?,?,?,?,?)`; let addSqlParams = [uuidv1(), w.sim, w.code, w.acactivation_date, w.expriation_date, new Date() .toLocaleDateString()]; await insert(addSql, addSqlParams); } catch (error) { console.log(`Error: ${error}`); } } console.log('All completed!'); })(); function insert(addSql, addSqlParams) { return new Promise((resolve, reject) => { try { connection.query(addSql, addSqlParams, function (err, result) { if (err) { console.log('[INSERT ERROR] - ', err.message); reject(err); } else { // console.log('INSERT ID:', result); console.log('INSERT ID:', addSqlParams[0]); resolve(); } }); } catch (err) { reject(err); } }) }
这样我们运行node + name.js 就可以向对应数据库插入数据了。我们需要配置node环境,将相关环境配置好,我们就可以按照步骤去导入数据了。最后大家如果想要了解更多json工具教程知识,敬请关注奇Q工具网。
推荐阅读: