2017-11-04 124 views
0

我是NodeJS的新手,並試圖找出如何從REST服務加載一些xml數據並將其轉換爲JSON,以便之後將其加載到我的視圖中。在NodeJS中將一些XML加載到JSON中

我試圖這樣做,查詢與Hapi API和加載到一個XML解析器,然後將其轉換爲JSON

執行以下操作似乎正確加載xml對象,並在打印它時實際顯示了一些JSON。 這是否意味着我不需要轉換爲JSON了?

const server = new Hapi.Server(); 
... 
server.route({ 
    method: 'GET', 
    path: '/', 
    handler: function (request, reply) { 
     Request.get('http://ws.seloger.com/search.xml?&idtt=2&idtypebien=2,1&ci=750056&pxmax=400000&tri=initial&naturebien=1,2&surfacemin=65search.xml?', 
      function (error, response, body) { 
      if (error) { 
       throw error; 
      } 

      var parse = require('xml-parser'); 
      var inspect = require('util').inspect;  
      var obj = parse(body); 
      console.log(inspect(obj, { colors: true, depth: 4 })); 

請注意,顯示的JSON也不是我正在尋找的,即。顯示與attributeschildren等:

{ declaration: { attributes: { version: '1.0', encoding: 'UTF-8' } }, 
root: 
{ name: 'recherche', 
    attributes: {}, 
    children: 
    [ { name: 'resume', 
     attributes: {}, 
     children: [], 
     content: '....' }, 

然而尋找的東西更像this細節(可能只是不同的表示)

回答

0

所以我想通了,我的問題似乎已涉及到解析器本身。使用這個我得到我需要的東西:

var parseString = require('xml2js').parseString; 
parseString(body, function (err, jsonData) { 
    reply.view('index', { result: body }); 
});