0

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

3
  • So, your object is being correctly parsed and you just need to take the string elements? It is more a algorithm question. Am I correct? Commented Aug 11, 2012 at 2:47
  • i would say yeah kinda. I just need the sting from the array to be returned. So the [], {} , and 12 need to be taken out so i can just return the strings Commented Aug 11, 2012 at 2:50
  • Ok. Take a look in my answer. I will try to do the way you are trying. Commented Aug 11, 2012 at 2:54

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

it looks par is json as string in his example
try console.log(typeof(par))
Parse the string that represents an array first.
console.log(typeof(par)) return string
try to start your example with var formdata = 'theArray"%3A"%5B%5B%5D%2C%5C"d%5C"%2C%5C"B%5C"%2C%7B%7D%2C%5C"b%5C"%2C12%2C%5C"A%5C"%2C%5C"c%5C"%5D"' :)
0

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"]

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.