Expressjs响应为JSON和Xml [英] Expressjs response as JSON and Xml

查看:182
本文介绍了Expressjs响应为JSON和Xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做什么::我正在尝试从数据库生成数据集的json和xml输出

What i am doing:: I am trying to generate json and xml output for a dataset from database

Express Code :: Here我正在尝试JSON响应

Express Code:: Here i am trying for JSON response

var express = require('express')
  , async = require('async')
  , http = require('http')
  , mysql = require('mysql'); 
  var xml = require('xml');

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'MyDatabase'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 3007);

app.use(express.static(__dirname + '/public/images'));

app.get('/Result/',function(request,response){
    var name_of_restaurants;

    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM mas_buf_type', function(err, rows, fields)
                {
                        console.log('Connection result error '+err);
                        name_of_restaurants = rows;
                        callback();
                });

 }

   // Send the response
], function ( error, results ) {


 response.json({'restaurants' : name_of_restaurants });



//response.set('Content-Type', 'text/xml');
//response.send(xml(name_of_restaurants));
} );

} );




http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));
});

我的输出 ::

{
    "restaurants": [
        {
            "Buf_Type_Id": 1,
            "Buf_Type_Name": "Breakfast"
        },
        {
            "Buf_Type_Id": 2,
            "Buf_Type_Name": "Lunch"
        },
        {
            "Buf_Type_Id": 3,
            "Buf_Type_Name": "Dinner"
        }
    ]
}

现在而不是

 response.json({'restaurants' : name_of_restaurants });

我添加了这些行以获取 XML 输出

I have added these lines to get XML output

response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));

输出 ::

<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Id>2</Buf_Type_Id>
<Buf_Type_Id>3</Buf_Type_Id>

我的问题 ::


  • 显然你可以看到这两个输出是不同的,我找不到
    第二列在xml输出

  • 如何解决这个

  • 我需要做哪些更改?

var express = require('express')
  , async = require('async')
  , http = require('http')
  , mysql = require('mysql'); 
  var xml = require('xml');

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'findmybuffet'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 3007);

app.use(express.static(__dirname + '/public/images'));

app.get('/Result/',function(request,response){
    var name_of_restaurants;

    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM mas_buf_type', function(err, rows, fields)
                {
                        console.log('Connection result error '+err);
                        name_of_restaurants = rows;
                        callback();
                });

 }

   // Send the response
], function ( error, results ) {


 //response.json({'restaurants' : name_of_restaurants });

response.set('Content-Type', 'text/xml');
//response.send(xml(name_of_restaurants));

response.send(xml({restaurants:[
    name_of_restaurants.map(function(r){
        return [ 
            { Buf_Type_Id: r.Buf_Type_Id },
            { Buf_Type_Name: r.Buf_Type_Name },
        ]
    })
]}));


} );

} );


http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));
});

输出 ::

<restaurants>
    <0>
        <Buf_Type_Id>1</Buf_Type_Id>
        <Buf_Type_Name>Breakfast</Buf_Type_Name>
    </0>
</restaurants>

另外,我们可以看到< 0> 获得生成....这不是必需的...如何删除这个?

Also clearly we can see <0> getting generated .... which is not required ...how to remove this ?

推荐答案

所以我环顾四周为您提供更好的对象到XML映射器。在我找到一个我喜欢的(它很容易使用,对你的应用程序是有意义的)之前,我尝试了三次。换一个旧的,并使用对象到xml

So I've looked around for a better object-to-XML mapper for you. I tried three before I found one that I liked (it's easy-to-use, and it makes sense for your application). Ditch the old one, and use object-to-xml instead:

var o2x = require('object-to-xml');

response.set('Content-Type', 'text/xml');
response.send(o2x({
    '?xml version="1.0" encoding="utf-8"?' : null,
    restaurants: {
        restaurant: name_of_restaurants
    }
}));

这篇关于Expressjs响应为JSON和Xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆