javascript - Returning JSON encode string from node.js - Stack Overflow

I am a plete noob in node.js and trying to learn it by using learnyounode. I am stuck at the last probl

I am a plete noob in node.js and trying to learn it by using learnyounode. I am stuck at the last problem of the 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" }.

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. What am I missing here?

Current Solution's Output:

[ hour: 7, minute: 27, second: 38 ]
[]
[]
[]
[ hour: 7, minute: 27, second: 38 ]
[]

I am a plete noob in node.js and trying to learn it by using learnyounode. I am stuck at the last problem of the 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" }.

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. What am I missing here?

Current Solution's Output:

[ hour: 7, minute: 27, second: 38 ]
[]
[]
[]
[ hour: 7, minute: 27, second: 38 ]
[]
Share Improve this question edited Apr 21, 2015 at 9:20 Scimonster 33.4k10 gold badges79 silver badges91 bronze badges asked Apr 21, 2015 at 7:30 fadedreamzfadedreamz 1,1561 gold badge10 silver badges19 bronze badges 5
  • What do you have in cur_url['query']['iso']? – Lewis Commented Apr 21, 2015 at 7:44
  • Can you create a fiddle pls. – marcel Commented Apr 21, 2015 at 7:47
  • 2 Try result={} instead of =[] – CFrei Commented Apr 21, 2015 at 7:48
  • @Tresdin it contains the iso format date with following format - YYYY:mm:DDTHH:MM:SS.MS – fadedreamz Commented Apr 22, 2015 at 10:42
  • @CFrei apparently this does the trick :) . ty – fadedreamz Commented Apr 22, 2015 at 10:48
Add a ment  | 

2 Answers 2

Reset to default 4
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. JavaScript accepts this, sort of, but JSON doesn't -- an array is an array, an object is an object.

If you initialize it as an object (var result = {};), JSON will recognize its properties and print them. As it is, JSON only sees an empty array.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744133542a4559948.html

相关推荐

  • javascript - Returning JSON encode string from node.js - Stack Overflow

    I am a plete noob in node.js and trying to learn it by using learnyounode. I am stuck at the last probl

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信