Javascript Node.js 中的 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11911438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:38:04  来源:igfitidea点击:

JSON array in Node.js

javascriptarraysjsonnode.js

提问by Chad

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. 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.

我必须在我的本地机器上创建一个响应请求的 Web 服务。客户端(不是我写的)会一次问我一个问题,我的服务器应该以适当的答案回应。

So the last thing i have to do is:

所以我要做的最后一件事是:

  • When a POSTrequest is made at location '/sort'with parameter 'theArray', sort the array removing all non-string valuesand return the resulting value as JSON.

    • theArrayparameter will be a stringified JSON Array
  • 当在位置'/sort'使用参数'theArray'发出POST请求时,对数组进行排序,删除所有非字符串值,并将结果值作为JSON返回。

    • theArray参数将是一个字符串化的 JSON 数组

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

因此,如果有人可以帮助我解决这个问题,并且如果可能的话,用一些书面代码做出回应,这些代码的设置方式已经可以与我设置代码的方式一起使用,那就太好了!谢谢

回答by davidbuzatto

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);

P.S. I didnt't pay attention. Your array was actually a string. Andrey, thanks for the tip.

PS我没注意。你的数组实际上是一个字符串。安德烈,谢谢你的提示。

回答by Andrey Sidorov

edit: one-liner (try it in repl!)

编辑:单行(在 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;

回答by Michelle Tilley

The replacerparameter of JSON.stringifydoesn't work quite like you're using it; check out the documentation on MDN.

replacer参数JSON.stringify不像你使用的那样工作;查看MDN 上的文档

You could use Array.prototype.filterto 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"]