如何在node.js中创建JSON数组并将值推入其中

时间:2015-12-02 07:33:52

标签: arrays json node.js

我正在尝试在数组中按键,值,然后使用JSON.stringify()将其转换为JSON。但它没有用。

我的node.js代码:

var jarray=[];
var json1=""; 

for (var i=0; i<jsonObj["Masters"]['Customer'].length; i++){

     var name= jsonObj["Masters"]['Customer'][i];
      var cust_name=name['Customer_Name'];
      var cust_code=name['Customer_Code'];

    connection.query("SELECT code FROM ((SELECT ccode AS code FROM customermaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT scode AS code FROM suppliermaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT stcode AS code FROM stockmaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT gcode AS code FROM generalledger2 WHERE companyid='AXWPM1658D') UNION ALL (SELECT bcode AS code FROM bankmaster WHERE companyid='AXWPM1658D'))p  where code='"+cust_code+"' ", function(err, rows, fields) {
     if (!err){

        var item ={"customer_name":cust_name ,"customer_code": cust_code };

      jarray.push(item);

    }
      else{
        console.log('Error while performing Query.'+err);
          }
    });

    }

json1=JSON.stringify({jarray:jarray});

var jsonObj1 = JSON.parse(json1); 
console.log("Json:"+jsonObj1);
console.log("arr length:"+jsonObj1.jarray.length);

打印:

Json:{ jarray: [] }
arr length:0

我的问题是如何在数组中推送值并将其转换为JSON数组?

2 个答案:

答案 0 :(得分:1)

您使用什么来发出SQL请求?看起来它有异步行为。如果是这样,那么当你对其进行字符串化时,它可能就是为什么你的数组仍然是空的原因。顺便说一句,在循环中发出SQL请求并不是很有效。也许用一个SQL请求获取所有结果会更好,这也可以更容易在回调中进行字符串化

答案 1 :(得分:1)

使用此:

var jarray = [];
var json1 = "";

var async = require('async');

async.forEachLimit(jsonObj["Masters"]['Customer'], 1, function(customer, callback) {

    var name = customer;
    var cust_name = name['Customer_Name'];
    var cust_code = name['Customer_Code'];

    connection.query("SELECT code FROM ((SELECT ccode AS code FROM customermaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT scode AS code FROM suppliermaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT stcode AS code FROM stockmaster WHERE companyid='AXWPM1658D') UNION ALL (SELECT gcode AS code FROM generalledger2 WHERE companyid='AXWPM1658D') UNION ALL (SELECT bcode AS code FROM bankmaster WHERE companyid='AXWPM1658D'))p  where code='" + cust_code + "' ", function(err, rows, fields) {
        if (!err) {

            var item = {
                "customer_name": cust_name,
                "customer_code": cust_code
            };

            jarray.push(item);
            callback();

        } else {
            callback(err);
            console.log('Error while performing Query.' + err);
        }
    });



}, function(err) {
    if (err) {
        console.log(err);
    } else {

        json1 = JSON.stringify({
            jarray: jarray
        });

        var jsonObj1 = JSON.parse(json1);
        console.log("Json:" + jsonObj1);
        console.log("arr length:" + jsonObj1.jarray.length);
    }
})