2017-09-05 95 views
-1

我從json對象中提取字段,但出於某種原因,我一直未定義。我在json數組「夜總會」內有一個數組。我想從該字段提取數據並將其放入數組中。我怎麼去解決它?這是我到目前爲止所嘗試的。我沒有使用明確的框架,我有點擔心,我如何解析JSON解析節點js中的json對象?

var TelegramBot = require('node-telegram-bot-api'); 
var request = require('request'); 
var http = require('http'); 
var express = require("express"); 
var app = express(); 

var fd = require("./Services.js"); 
var bodyParser = require("body-parser"); 
app.use(bodyParser.urlencoded({extended: false})); 
app.use(bodyParser.json()); 
const TOKEN = process.env.TELEGRAM_TOKEN || '****************'; 
http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('Hello, world! [helloworld sample;'); 
}).listen(3009); 

telegram = new TelegramBot(TOKEN, { polling: true }); 
telegram.on("text",function (message,req,res) { 

    var messagetext = message.text; 
    var receiver = message.chat.id; //the user receiving the response from the bot 
    var timestamp = message.date; //timestamp 
    var msgid = message.message_id;//message id 
    var sender = message.from.id; //id of the telegram bot 
    console.log("message",messagetext); 
    switch (messagetext) { 
     case "Menu": 
      telegram.sendMessage(sender,"Enter the name of the menu that you would like to choose"); 
      fd.itemcategory().then(function (v) { 
       console.log(v); 
       for (var i = 0; i < 5; i++) { 
        telegram.sendMessage(sender, v[i]); 
       } 
      }); 
      break; 

     case "Nightclub": 
      telegram.sendMessage(sender,"Here are some of the best nightlife in Nairobi"); 
      fd.categorydata("Nightclub").then(function(v){ 
       var obj = v; 


       console.log("entered",obj.info); 




      }); 
      break; 



    } 









}); 







This is the response I am receiving from the api 
    { 
     "info": { 
      "response": "sucess", 
      "nightclub": [ 
       "fjfjkfkf", 
       "jfkfkfkf", 
       "fujfjkfkf", 
       "fjfjfklf", 
       "fjfjfkkf" 
      ] 
     } 
    } 

這是我在控制檯中看到 -

entered undefined 
+0

v.info.nightclub這應該給你夜總會 –

+0

@Dinesh: - 我收到未定義 – Rachel

+0

做的console.log(V)和檢查什麼你得到? –

回答

2

你將不得不使用變量

v.info.nightclub 

let obj = { 
 
    "info": { 
 
     "response": "sucess", 
 
     "nightclub": [ 
 
      "fjfjkfkf", 
 
      "jfkfkfkf", 
 
      "fujfjkfkf", 
 
      "fjfjfklf", 
 
      "fjfjfkkf" 
 
     ] 
 
    } 
 
} 
 

 
console.log(obj.info.nightclub);
從評論它表明你得到一個字符串作爲輸入,這樣只需使用

obj = JSON.parse(obj) 

把它轉換成一個有效的JSON對象

0

爲了得到它在數組中,你可以通過對每個運行(或jquery $ .each)你指向v.info.nightclub的地方。

像這樣的事情

var nightclubs = [] 
$.each(v.info, function(index, entry{ 
nightclubs.push(entry.info.nightclub); 
} 
console.log(nightclubs)