简体   繁体   English

Node.js中的JSON数组

[英]JSON array in Node.js

I have been trying to figure this out for the past week and everything that i try just doesn't seem to work. 在过去的一周中,我一直试图弄清楚这一点,而我尝试的一切似乎都没有用。

I have to create a web service on my local box that responds to requests. 我必须在响应请求的本地框上创建一个Web服务。 The client (that i did not write) will ask my service one question at a time, to which my server should respond with an appropriate answer. 客户端(我未写过)将一次向我的服务提出一个问题,我的服务器应以适当的答案对此进行响应。

So the last thing i have to do is: 因此,我要做的最后一件事是:

  • When a POST request is made at location '/sort' with parameter 'theArray' , sort the array removing all non-string values and return the resulting value as JSON . 当使用参数'theArray'在位置'/ sort'发出POST请求时,对数组进行排序以除去所有非字符串值 ,并将结果值返回为JSON

    • theArray parameter will be a stringified JSON Array theArray参数将是一个字符串化的JSON Array

From going through trail and error i have found out that the parameters supplied is: 从经历的错误和错误中,我发现提供的参数是:

{"theArray":"[[],\"d\",\"B\",{},\"b\",12,\"A\",\"c\"]"}

I have tried many different thing to try to get this to work. 我尝试了许多不同的方法来尝试使它起作用。 But the closest thing i can get is it only returning the same thing or nothing at all. 但是我能得到的最接近的东西是它只返回相同的东西或什么都没有返回。 This is the code that i am using to get those results: 这是我用来获得这些结果的代码:

case '/sort':
        if (req.method == 'POST') {
            res.writeHead(200,{
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            });
            var fullArr = "";
                req.on('data', function(chunk) {
                    fullArr += chunk;
                    });
                req.on('end', function() {
                            var query = qs.parse(fullArr);
                            var strin = qs.stringify(query.theArray)
                            var jArr = JSON.parse(fullArr);
                    console.log(jArr); // Returns undefided:1 
                            var par = query.theArray;
                    console.log(par); // returns [[],"d","B",{},"b",12,"A","c"]

                                function censor(key) {
                                    if (typeof key == "string") {
                                            return key;
                                        } 
                                        return undefined;
                                        }
                        var jsonString = JSON.stringify(par, censor);
                   console.log(jsonString); // returns ""
                });         
                    res.end();


        };

break;

Just to clarify what I need it to return is ["d","B","b","A","c"] 只是为了澄清我需要它返回的是["d","B","b","A","c"]

So if someone can please help me with this and if possible responded with some written code that is kinda set up in a way that would already work with the way i have my code set up that would be great! 因此,如果有人可以帮助我,并在可能的情况下以某种书面代码作为响应,而这种书面代码的设置方式已经可以与我设置代码的方式配合使用,那就太好了! Thanks 谢谢

Edit: Try this: 编辑:试试这个:

var query = {"theArray":"[[],\"d\",\"B\",{},\"b\",12,\"A\",\"c\"]"};
var par = JSON.parse(query.theArray);
var stringArray = [];
for ( var i = 0; i < par.length; i++ ) {
    if ( typeof par[i] == "string" ) {
        stringArray.push(par[i]);
    }
}
var jsonString = JSON.stringify( stringArray );
console.log(jsonString);

PS I didnt't pay attention. PS我没有注意。 Your array was actually a string. 您的数组实际上是一个字符串。 Andrey, thanks for the tip. 安德烈,谢谢你的提示。

edit: one-liner (try it in repl!) 编辑:单线(请尝试一下!)

JSON.stringify(JSON.parse(require('querystring').parse('theArray=%5B%5B%5D%2C"d"%2C"B"%2C%7B%7D%2C"b"%2C12%2C"A"%2C"c"%5D').theArray).filter(function(el) {return typeof(el) == 'string'}));

code to paste to your server: 粘贴到服务器的代码:

case '/sort':
        if (req.method == 'POST') {
            buff = '';
            req.on('data', function(chunk) { buff += chunk.toString() });
            res.on('end', function() {
              var inputJsonAsString = qs.parse(fullArr).theArray;
              // fullArr is x-www-form-urlencoded string and NOT a valid json (thus undefined returned from JSON.parse)
              var inputJson = JSON.parse(inputJsonAsString);
              var stringsArr = inputJson.filter(function(el) {return typeof(el) == 'string'});
              res.writeHead(200,{
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
              });
              res.end(JSON.stringify(stringsArr));
        };
break;

The replacer parameter of JSON.stringify doesn't work quite like you're using it; JSON.stringifyreplacer参数不能像您正在使用的那样工作; check out the documentation on MDN . 查看有关MDN的文档

You could use Array.prototype.filter to filter out the elements you don't want: 您可以使用Array.prototype.filter过滤掉不需要的元素:

var arr = [[],"d","B",{},"b",12,"A","c"];
arr = arr.filter(function(v) { return typeof v == 'string'; });
arr // => ["d", "B", "b", "A", "c"]

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

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