JSON array in Node.js

2020-04-01 03:06发布

问题:

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.

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 parameter will be a stringified 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"]

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

回答1:

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.



回答2:

The replacer parameter of JSON.stringify doesn't work quite like you're using it; check out the documentation on MDN.

You could use Array.prototype.filter to filter out the elements you don't want:

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


回答3:

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;