【问题标题】:Converting sql data to json but json file include recordset将 sql 数据转换为 json 但 json 文件包含记录集
【发布时间】:2021-08-09 19:44:36
【问题描述】:

我正在尝试将 sql 数据转换为 json 数据,但是当文件完成时,我得到一些“记录集”这是什么以及如何摆脱它。

  app.post("/Employees",function (req, res)  {
           const sql = require("mssql");
    
           const config = {
          
            server: 'HOST',  //update me
            user: 'user', //update me
            password: 'pass',  //update me
            database: 'db',
            trustServerCertificate: true
           }
    
           // var to store file name 
           var d = new Date();
             var fileName = "db_"+d.getDate()+"_"+d.getMonth()+"_"+d.getTime();
           sql.connect(config, function(err, data) {
            
             if(err) console.log(err);
               let sqlRequest = new sql.Request();
    
               let sqlQuery = "select * from dbo.cust where name like 'aa%' AND surname like 'a%' AND branch='bsmtr';";
               sqlRequest.query(sqlQuery, function (err, data) {
                 if(err) console.log(err) 
                 console.log(data);
               
                 fs.writeFile(`json_files/${fileName}.json`, JSON.stringify(data, replacer, space), err => err && console.log(err));
                 sql.close();
               });
           });
          
           res.send("The JSON file is downloaded please find it in the Json directory by the name "+fileName+".JSON");
        });

-----这就是我获取 json 的方式 .---

{
    "recordsets": [
        [
            {
                "rowno": 294680503,
                "rowno_custcrm_crm": 0,
                "has_custansp_ansp": 0,
                "rowno_custemt_emt": 0,
                "rowno_custmtm_mtm": 0,
                "rowno_custm2mc_m2mcu": 0,
                "has_custext_ext": 0,
                "rowno_custcloa_cloa": 0,
                "has_custalrt_alrt": 0,
                "rowno_custemcc_emcc": 0,
                "rowno_custiop_iop": 0,
                "has_custcds_cds": 0,
                "has_custltv_ltv": 0,
                "rowno_custoir_oir": 0,
                "rowno_custorcc_orcc": 0,
                "rowno_custcmps_cmps": 0
            }
        ]
    ],
   
    "output": {},
    "rowsAffected": 1
}

请告诉我如何摆脱记录集、方括号、输出和行影响

【问题讨论】:

    标签: javascript sql node.js json reactjs


    【解决方案1】:

    好吧,您只需要将您实际想要放入文件的数据进行字符串化。例如如果你想要recordset 的内容,你需要调用JSON.stringify(data.recordset, replacer, space)。如果你想把你拥有的那个元素放在recordset 中,你需要使用JSON.stringify(data.recordsets[0][0], replacer, space)

    【讨论】:

    • 它有效,但我仍然得到方括号。我该如何摆脱它?谢谢。
    • 方括号表示您正在保存一个数组。只需再深入一个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2022-08-12
    • 2017-04-01
    • 2020-10-30
    相关资源
    最近更新 更多