JSON array in Node.js

后端 未结 3 1848
情书的邮戳
情书的邮戳 2021-01-17 05: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 re

相关标签:
3条回答
  • 2021-01-17 05:28

    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;
    
    0 讨论(0)
  • 2021-01-17 05:29

    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"]
    
    0 讨论(0)
  • 2021-01-17 05:53

    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.

    0 讨论(0)
提交回复
热议问题