简体   繁体   English

从node.js返回JSON编码字符串

[英]Returning JSON encode string from node.js

I am a complete noob in node.js and trying to learn it by using learnyounode. 我是node.js中的一个完整的菜鸟,并试图通过使用learnyounode来学习它。 I am stuck at the last problem of the learnyounode - [HTTP JSON API SERVER]. 我陷入了learnyounode的最后一个问题 - [HTTP JSON API SERVER]。
Here the tutorial will call a url to provide a time (as iso standard) and the node.js server should return the json reply in (k,v) where pair will be k = { "hour", "minute", "second" }. 这里教程将调用一个url来提供一个时间(作为iso标准),node.js服务器应该返回(k,v)中的json回复,其中pair将是k = {“hour”,“minute”,“second” “}。

My solution goes like below - 我的解决方案如下 -

var http = require('http');
var url = require('url');

function get_json(str) {
        var result = [];
        str = str.substr(str.lastIndexOf('T') + 1);
        result['hour'] = Number(str.substring(0, str.indexOf(':')));
        str = str.substring(str.indexOf(':') + 1);
        result['minute'] = Number(str.substring(0, str.indexOf(':')));
        str = str.substring(str.indexOf(':') + 1);
        result['second'] = Number(str.substring(0, str.indexOf('.')));
        return result;
}

function get_unix(str) {
        var result = get_json(str);
        result['unix'] =  ((result['hour'] * 3600000) +
                (result['min'] * 60000) + (result['sec'] * 1000));
        return result;
}

var server = http.createServer(function (req, res) {
        if (req.method != 'GET') {
                return res.write('{ "error": "query-failed" }');
        }
        var cur_url = url.parse(req.url, true);
        if (cur_url['pathname'] == '/api/parsetime') {
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.write(JSON.stringify(get_json(cur_url['query']['iso'])));
        } else if (cur_url['pathname'] == '/api/unixtime') {
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.write(JSON.stringify(get_unix(cur_url['query']['iso'])));
        }
        console.log(get_json(cur_url['query']['iso']));
        console.log(JSON.stringify(get_json(cur_url['query']['iso'])));
        res.end();
});

server.listen(process.argv[2]);

But the solution is not working correctly because JSON.stringify() is returning empty [] string. 但解决方案无法正常工作,因为JSON.stringify()返回空[]字符串。 What am I missing here? 我在这里错过了什么?

Current Solution's Output: 当前解决方案的输出:

[ hour: 7, minute: 27, second: 38 ]
[]
[]
[]
[ hour: 7, minute: 27, second: 38 ]
[]
function get_json(str) {
        var result = [];
        str = str.substr(str.lastIndexOf('T') + 1);
        result['hour'] = Number(str.substring(0, str.indexOf(':')));
        str = str.substring(str.indexOf(':') + 1);
        result['minute'] = Number(str.substring(0, str.indexOf(':')));
        str = str.substring(str.indexOf(':') + 1);
        result['second'] = Number(str.substring(0, str.indexOf('.')));
        return result;
}

You are initializing result as an array, but treating it as an object. 您正在将result初始化为数组,但将其视为对象。 JavaScript accepts this, sort of, but JSON doesn't -- an array is an array, an object is an object. JavaScript接受这种,但JSON没有 - 数组是数组,对象是对象。

If you initialize it as an object ( var result = {}; ), JSON will recognize its properties and print them. 如果将其初始化为对象( var result = {}; ),JSON将识别其属性并打印它们。 As it is, JSON only sees an empty array. 实际上,JSON只能看到一个空数组。

I have changed some places. 我改变了一些地方。

function get_json(str) {
    str = new Date(str).toLocaleTimeString();

    var arr = str.split(":");

    var result = {};
    result['hour'] = +arr[0];
    result['minute'] = +arr[1];
    result['second'] = +arr[2];

    return result;
}

function get_unix(str) {
    return {"unixtime": +(new Date(str))};
}

+ converts string to int +字符串转换为int

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

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