JSON array in Node.js

后端 未结 3 1850
情书的邮戳
情书的邮戳 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;
    

提交回复
热议问题