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

前端之家收集整理的这篇文章主要介绍了javascript – 如何将x-www-form-urlencoded字符串转换为JSON?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
应用程序的例子/ x-www-form-urlencoded的字符串
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"]
        };

解决方法

我最近一直在处理这个问题:我不得不解析可能包含最多5层的对象的数据.我需要代码才能处理相当复杂的数据,但不能像RFC = 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(/\](.+?)(,$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检查,当忽略空白时,.和[^ …]并接受.总而言之,我认为这是可以接受的.

猜你在找的JavaScript相关文章