繁体   English   中英

解析节点js中的json对象?

[英]Parsing a json object in node js?

我正在从json对象提取字段,但由于某些原因,我一直未定义。 我在json数组“ nightclub”中有一个数组。 我想从该字段中提取数据并将其放入数组中。 我该怎么办? 这是我到目前为止尝试过的。 我没有使用express框架,我有点担心我如何解析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

您将不得不使用变量

v.info.nightclub

 let obj = { "info": { "response": "sucess", "nightclub": [ "fjfjkfkf", "jfkfkfkf", "fujfjkfkf", "fjfjfklf", "fjfjfkkf" ] } } console.log(obj.info.nightclub); 
从注释中可以看出,您正在获取字符串作为输入,因此只需使用

 obj = JSON.parse(obj) 

将其转换为有效的json对象

为了得到一个数组,可以为每个指向v.info.nightclub的位置(或jquery $ .each)运行它。

像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM