当我想构建像下面这样的JSON对象时,如何使用节点回调

时间:2013-11-11 13:37:19

标签: json node.js

我刚开始用node.js编码,我知道node.js是异步的,但不知道如何处理这个问题。

我正在查询mysql并构建一​​个JSON,如下所示:

 var mysql = require('mysql');
    var async = require('async');
 var connection = mysql.createConnection({
 host : 'localhost',
 user : 'root',
 password : '',
 database : 'hungryna_hungry_database',
 insecureAuth : true
});
var obj={
  "zone":[],
};
var zonearray=new Array();
connection.query('SELECT id,name FROM zone LIMIT 100', function(err, rows) {
 var ck=new Array();
  for(i=0; i < rows.length; i++){
      var zoneObj={};
      var zone=rows[i];
      zoneObj.id=zone.id;
      zoneObj.name=zone.name;
           ck.push({
                "id":zoneObj.id,
                "name":zoneObj.name

            });
            build_actor(zoneObj.id,function(err,area){
              if(!err){

                     //zonearray=ck;
                      //obj.zone=zonearray;
                      console.log(JSON.stringify(ck));
                }
            });

   }
 });

 function build_actor(zoneid,cb){
    connection.query('SELECT id,name FROM area WHERE zone_id='+zoneid+';',
      function(err,       a) {


       var ak =new Array();
       for(var i in a)
       {
            ak.push({
                "id":a[i].id,
                "name":a[i].name
            });
       }

       cb (null,ak);

    });

我的输出如下:

    [{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
    4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]
   [{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
   4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]
   [{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
   4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]

我想要的输出如下:

       {
       "zone1":[
  {
     "id":1,
     "name":"a",
     "area":[
        {
            "id":1,
            "name":"area1"
        },
        {
            "id":2,
            "name":"area2"
        }
     ]  
   },
   {
     "id":2,
     "name":"b",
     "area":[
        {
            "id":1,
            "name":"area1"
        },
        {
            "id":2,
            "name":"area2"
        }
     ]  
   }
      ]
    }

0 个答案:

没有答案