如何将x-www-form-urlencoded字符串转换为JSON?

时间:2011-01-12 17:39:09

标签: javascript json

application / x-www-form-urlencoded string

的示例
CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4

进入JSON

var gamePlayData = {
            CorrelationId: gameId,
            PickedNumbers: ["1","2","3","4"]
        };

9 个答案:

答案 0 :(得分:12)

如果您正在使用节点或浏览器化,则可以使用qs

var qs = require('qs')
var encodedString = "CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4" 

console.log(qs.parse(encodedString))
// { CorrelationId: '1', PickedNumbers: [ '1', '2', '3', '4' ] }

答案 1 :(得分:10)

我最近一直在处理这个问题:我必须解析可能包含最多嵌套5级的对象的数据。我需要代码能够处理相当复杂的数据,但不能解码像id=213这样简单的URI。

我花了很长时间在谷歌上,试图找到一个(半)优雅的解决方案,这个问题不断出现。由于它每天获得1次观看(给予或接受),我决定在此发布我的解决方案,希望它可以帮助某人:

function form2Json(str)
{
    "use strict";
    var obj,i,pt,keys,j,ev;
    if (typeof form2Json.br !== 'function')
    {
        form2Json.br = function(repl)
        {
            if (repl.indexOf(']') !== -1)
            {
                return repl.replace(/\](.+?)(,|$)/g,function($1,$2,$3)
                {
                    return form2Json.br($2+'}'+$3);
                });
            }
            return repl;
        };
    }
    str = '{"'+(str.indexOf('%') !== -1 ? decodeURI(str) : str)+'"}';
    obj = str.replace(/\=/g,'":"').replace(/&/g,'","').replace(/\[/g,'":{"');
    obj = JSON.parse(obj.replace(/\](.+?)(,|$)/g,function($1,$2,$3){ return form2Json.br($2+'}'+$3);}));
    pt = ('&'+str).replace(/(\[|\]|\=)/g,'"$1"').replace(/\]"+/g,']').replace(/&([^\[\=]+?)(\[|\=)/g,'"&["$1]$2');
    pt = (pt + '"').replace(/^"&/,'').split('&');
    for (i=0;i<pt.length;i++)
    {
        ev = obj;
        keys = pt[i].match(/(?!:(\["))([^"]+?)(?=("\]))/g);
        for (j=0;j<keys.length;j++)
        {
            if (!ev.hasOwnProperty(keys[j]))
            {
                if (keys.length > (j + 1))
                {
                    ev[keys[j]] = {};
                }
                else
                {
                    ev[keys[j]] = pt[i].split('=')[1].replace(/"/g,'');
                    break;
                }
            }
            ev = ev[keys[j]];
        }
    }
    return obj;
}

我已经测试了它,数据类似于下面的字符串(4级深度):

str  = "id=007&name[first]=james&name[last]=bond&name[title]=agent&personalia[occupation]=spy&personalia[strength]=women&personalia[weakness]=women&tools[weapons][close][silent]=garrot&tools[weapons][medium][silent]=pistol_supressed&tools[weapons][medium][loud]=smg&tools[weapons][far][silent]=sniper&tools[movement][slow]=foot&tools[movement][far]=DBS";

整齐地返回一个对象,当通过JSON.stringify传递出来时,就像这样:

{"id":"007","name":{"title":"agent","first":"james","last":"bond"},"personalia":{"weakness":"women","occupation":"spy","strength":"women"},"tools":{"movement":{"far":"DBS","slow":"foot"},"weapons":{"close":{"silent":"garrot"},"medium":{"silent":"pistol_supressed","loud":"smg"},"far":{"silent":"sniper"}}}}

当忽略空格.[^...]并接受++时,它会传递JSlint检查。总而言之,我认为这是可以接受的。

答案 2 :(得分:8)

现在这是Node.js的核心模块:https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options

var qs = require('querystring')

var json = qs.parse('why=not&sad=salad')
    // { why: 'not', sad: 'salad' }

也适用于编码字符:

var json2 = qs.parse('http%3A%2F%2Fexample.com&sad=salad')
    // { url: 'http://example.com', sad: 'salad' }

答案 3 :(得分:5)

以下代码可以解决这个问题:

var str = 'CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4';
var keyValuePairs = str.split('&');
var json = {};
for(var i=0,len = keyValuePairs.length,tmp,key,value;i <len;i++) {
    tmp = keyValuePairs[i].split('=');
    key = decodeURIComponent(tmp[0]);
    value = decodeURIComponent(tmp[1]);
    if(key.search(/\[\]$/) != -1) {
        tmp = key.replace(/\[\]$/,'');
        json[tmp] = json[tmp] || [];
        json[tmp].push(value);
    }
    else {
        json[key] = value;
    }
}

答案 4 :(得分:2)

这是一种纯JavaScript方式。 JavaScript框架也可能会帮助您解决这个问题。 编辑:仅仅为了踢,我也投入了字典解析。见第二个例子。

function decodeFormParams(params) {
  var pairs = params.split('&'),
      result = {};

  for (var i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('='),
        key = decodeURIComponent(pair[0]),
        value = decodeURIComponent(pair[1]),
        isArray = /\[\]$/.test(key),
        dictMatch = key.match(/^(.+)\[([^\]]+)\]$/);

    if (dictMatch) {
      key = dictMatch[1];
      var subkey = dictMatch[2];

      result[key] = result[key] || {};
      result[key][subkey] = value;
    } else if (isArray) {
      key = key.substring(0, key.length-2);
      result[key] = result[key] || [];
      result[key].push(value);
    } else {
      result[key] = value;
    }
  }

  return result;
}

decodeFormParams("CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4");
// => {"CorrelationId":"1","PickedNumbers":["1","2","3","4"]}

decodeFormParams("a%5Bb%5D=c&a%5Bd%5D=e");
// => {"a":{"b":"c","d":"e"}}

答案 5 :(得分:1)

试试这个 - &gt;

// convert string to object
str = 'a=6&id=99';
var arr = str.split('&');
var obj = {};
for(var i = 0; i < arr.length; i++) {
    var bits = arr[i].split('=');
    obj[bits[0]] = bits[1];
}
//alert(obj.a);
//alert(obj.id);

// convert object back to string
str = '';
for(key in obj) {
    str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1); 
alert(str);

或者使用此(JQuery)http://api.jquery.com/jQuery.param/

答案 6 :(得分:0)

你需要与jQuery.param相反。其中一个选项是http://benalman.com/code/projects/jquery-bbq/examples/deparam/

答案 7 :(得分:0)

单线:

let s = 'a=1&b=2&c=3';

Object.fromEntries(
  s.split('&')
   .map(s => s.split('='))
   .map(pair => pair.map(decodeURIComponent)))

// -> {a: "1", b: "2", c: "3"}

如果你想将重复的参数表示为数组:

let s = 'a=1&b=2&c[]=3&c[]=4&c[]=5&c[]=6';

s
  .split('&')
  .map(s => s.split('='))
  .map(pair => pair.map(decodeURIComponent))
  .reduce((memo, [key, value]) => { 
    if (!(key in memo)) { memo[key] = value; } 
    else { 
      if (!(memo[key] instanceof Array)) 
        memo[key] = [memo[key], value]; 
        else 
        memo[key].push(value); 
      } 
    return memo; 
}, {})

// -> {"a":"1","b":"2","c[]":["3","4","5","6"]}

答案 8 :(得分:-1)

public static void Main()

{

string str =“ RESULT = 0&PNREF = A10AABBF8DF2&RESPMSG = Approved&AUTHCODE = 668PNI&PREFPSMSG =未触发任何规则&POSTFPSMSG =未触发任何规则”;

    var sr = str.Replace("&", "=");

    string[] sp = sr.Split('=');

    var spl = sp.Length;

    int n = 1;

    var ss = "{";

    for (var k = 0; k < spl; k++)
    {
        if (n % 2 == 0)
        {
            if (n == spl)
            {
                ss += '"' + sp[k] + '"';
            }
            else
            {
                ss += '"' + sp[k] + '"' + ",";
            }
        }
        else
        {
            ss += '"' + sp[k] + '"' + ":";
        }
        n++;
    }
    ss += "}";
    Console.WriteLine(ss);
}