如何编写JavaScript函数处理嵌套JSON并插入SQL表?
解决方案
针对嵌套结构的JSON,你需要逐层遍历数据,将嵌套键值对展开成SQL表所需的扁平格式,再生成对应的INSERT语句。以下是具体实现和建议:
核心实现代码
function generateInsertQuery(inputData) { let query = ""; // 遍历外层data数组中的每个用户条目 inputData.data.forEach(user => { const name = user.name; // 遍历用户的每个detail类别(contact、address等) Object.entries(user).forEach(([detail, detailObj]) => { // 跳过name字段,只处理嵌套对象类型的字段 if (detail === 'name' || typeof detailObj !== 'object') return; // 遍历当前detail下的每个type和value Object.entries(detailObj).forEach(([type, value]) => { query += ` begin insert into [dbname].[dbo].[table] (name, detail, type, value) values('${name}', '${detail}', '${type}', '${value}') end `; }); }); }); return query.trim(); } // 测试输入数据 const input = { "data": [{ "name": "John", "contact": { "phone": "987-654-3210", "email": "john123@xyz.com" }, "address": { "city": "Berlin", "country": "Germany" } }] }; // 生成并输出查询语句 console.log(generateInsertQuery(input));
代码逻辑说明
- 遍历
input.data数组中的每个用户对象,提取用户名name; - 遍历用户对象的所有键,筛选出
contact、address这类嵌套对象作为detail; - 遍历每个
detail对象内的键值对,键对应SQL表的type,值对应value; - 逐个拼接INSERT语句,最终生成符合要求的SQL脚本。
关键安全提示
你当前的字符串拼接方式存在SQL注入风险,如果输入包含单引号、分号等特殊字符,会导致SQL语法错误甚至被恶意利用。建议改用参数化查询,以Node.js的mssql库为例:
const sql = require('mssql'); async function insertData(inputData) { const pool = await sql.connect('你的数据库连接字符串'); const request = pool.request(); for (const user of inputData.data) { const name = user.name; for (const [detail, detailObj] of Object.entries(user)) { if (detail === 'name' || typeof detailObj !== 'object') continue; for (const [type, value] of Object.entries(detailObj)) { // 使用参数化查询避免注入 request.input('name', sql.VarChar, name); request.input('detail', sql.VarChar, detail); request.input('type', sql.VarChar, type); request.input('value', sql.VarChar, value); await request.query(` insert into [dbname].[dbo].[table] (name, detail, type, value) values(@name, @detail, @type, @value) `); } } } }
参数化查询会自动处理特殊字符,大幅提升代码安全性和健壮性。
内容的提问来源于stack exchange,提问作者Shan
相关产品推荐
相关产品推荐

