Javascript 将键值字符串解析为 JSON

我目前正在尝试创建一个 UDF,以将基于 Web 流量的键值对字符串拆分为 JSON。


我已经设法输出一个 JSON 对象,但我希望能够根据键的索引号购买或查看的产品数量动态添加嵌套项目。


当仅查看产品时,字符串中始终只有一个产品。只有当它是一个交易时,它才不止一个,但我认为最好符合 json 的结构,然后根据交易 ID 的存在来识别购买或查看。例如:


购买的物品:


sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58

输出应如下所示:


[

   {

      "sessionid":12345,

      "transactionid":555555,

      "transactionamount":58

   },

   [

      {

         "productline":1,

         "product":"apples",

         "productprice":12,

         "productqty":1

      },

      {

         "productline":2,

         "product":"pears",

         "productprice":23,

         "productqty":2

      }

   ]

]

查看的项目:


sessionid=12345&product1=apples&productprice1=12&product1qty=1&product2=梨&productprice2=23&product2qty=3


[

   {

      "sessionid":12345,

      "transactionid":0,

      "transactionamount":0

   },

   [

      {

         "productline":1,

         "product":"apples",

         "productprice":12,

         "productqty":1

      }

   ]

]

结果我将能够从 JSON 解析为 SQL 表中的一致表。


到目前为止,我尝试过的只是解析字符串,但在 SQL 中创建表并不理想,因为购买次数可能会有所不同:


var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";


function splitstring(queryString) {

    var dictionary = {};


    if (queryString.indexOf('?') === 0) {

        queryString = queryString.substr(1);

    }


    var parts = queryString.split('&');


    for (var i = 0; i < parts.length; i++) {

        var p = parts[i];

        // Step 2: Split Key/Value pair

        var keyValuePair = p.split('=');

        var key = keyValuePair[0];

        var value = keyValuePair[1];


        dec_val = decodeURIComponent(value);

        final_value = dec_val.replace(/\+/g, ' ');

        dictionary[key] = final_value;

    }


    return (dictionary);

}


console.log(splitstring(string));

提前致谢!!!


慕田峪4524236
浏览 229回答 2
2回答

慕码人2483693

感觉使用更好的参数命名约定会不那么笨拙,但这是我的看法......function parseString(string) {&nbsp; &nbsp; var string = string || '',&nbsp; &nbsp; &nbsp; &nbsp; params, param, output, i, l, n, v, k, pk;&nbsp; &nbsp; params = string.split('&');&nbsp; &nbsp; output = [{},&nbsp; &nbsp; &nbsp; &nbsp; []&nbsp; &nbsp; ];&nbsp; &nbsp; for (i = 0, l = params.length; i < l; i++) {&nbsp; &nbsp; &nbsp; &nbsp; param = params[i].split('=');&nbsp; &nbsp; &nbsp; &nbsp; n = param[0].match(/^product.*?([0-9]+).*/);&nbsp; &nbsp; &nbsp; &nbsp; v = decodeURIComponent(param[1] || '');&nbsp; &nbsp; &nbsp; &nbsp; if (n && n[1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k = n[1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[1][k] = output[1][k] || {};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[1][k]['productline'] = k;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pk = n[0].replace(/[0-9]+/, '');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[1][k][pk] = v;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[0][param[0]] = v;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; output[1] = output[1].filter(Boolean);&nbsp; &nbsp; return output;}var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";console.log(parseString(string));输出:[&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "sessionid": "12345",&nbsp; &nbsp; &nbsp; &nbsp; "transactionid": "555555",&nbsp; &nbsp; &nbsp; &nbsp; "transactionamount": "58"&nbsp; &nbsp; },&nbsp; &nbsp; [{&nbsp; &nbsp; &nbsp; &nbsp; "productline": "1",&nbsp; &nbsp; &nbsp; &nbsp; "product": "1",&nbsp; &nbsp; &nbsp; &nbsp; "productprice": "12"&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; "productline": "2",&nbsp; &nbsp; &nbsp; &nbsp; "product": "3",&nbsp; &nbsp; &nbsp; &nbsp; "productprice": "23"&nbsp; &nbsp; }]]

蝴蝶刀刀

可能有更好的方法来做到这一点,但我只是按照我的想法编写了代码var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";function splitstring(queryString) {&nbsp; &nbsp; var dictionary = {};&nbsp; &nbsp; if (queryString.indexOf('?') === 0) {&nbsp; &nbsp; &nbsp; &nbsp; queryString = queryString.substr(1);&nbsp; &nbsp; }&nbsp; &nbsp; var parts = queryString.split('&');&nbsp; &nbsp; for (var i = 0; i < parts.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var p = parts[i];&nbsp; &nbsp; &nbsp; &nbsp; // Step 2: Split Key/Value pair&nbsp; &nbsp; &nbsp; &nbsp; var keyValuePair = p.split('=');&nbsp; &nbsp; &nbsp; &nbsp; var key = keyValuePair[0];&nbsp; &nbsp; &nbsp; &nbsp; var value = keyValuePair[1];&nbsp; &nbsp; &nbsp; &nbsp; dec_val = decodeURIComponent(value);&nbsp; &nbsp; &nbsp; &nbsp; final_value = dec_val.replace(/\+/g, ' ');&nbsp; &nbsp; &nbsp; &nbsp; dictionary[key] = final_value;&nbsp; &nbsp; }&nbsp; &nbsp; return (dictionary);}function process(obj) {&nbsp; &nbsp; let i = 1;&nbsp; &nbsp; const products = [];&nbsp; &nbsp; while(obj.hasOwnProperty(`product${i}`)) {&nbsp; &nbsp; &nbsp; &nbsp; products.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [`product`]: obj[`product${i}`],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [`productprice`]: obj[`productprice${i}`],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [`productqty`]: obj[`product${i}qty`]&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; delete obj[`product${i}`];&nbsp; &nbsp; &nbsp; &nbsp; delete obj[`productprice${i}`];&nbsp; &nbsp; &nbsp; &nbsp; delete obj[`product${i}qty`];&nbsp; &nbsp; &nbsp; &nbsp; ++i;&nbsp; &nbsp; }&nbsp; &nbsp; return [obj, products];}console.log(process(splitstring(string)));顺便说一句,如果这是在浏览器中,那么splitstring可以“替换”为const splitstring = string => Object.fromEntries(new URLSearchParams(string).entries());var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";function process(string) {&nbsp; const splitstring = queryString => {&nbsp; &nbsp; var dictionary = {};&nbsp; &nbsp; if (queryString.indexOf('?') === 0) {&nbsp; &nbsp; &nbsp; queryString = queryString.substr(1);&nbsp; &nbsp; }&nbsp; &nbsp; var parts = queryString.split('&');&nbsp; &nbsp; for (var i = 0; i < parts.length; i++) {&nbsp; &nbsp; &nbsp; var p = parts[i];&nbsp; &nbsp; &nbsp; // Step 2: Split Key/Value pair&nbsp; &nbsp; &nbsp; var keyValuePair = p.split('=');&nbsp; &nbsp; &nbsp; var key = keyValuePair[0];&nbsp; &nbsp; &nbsp; var value = keyValuePair[1];&nbsp; &nbsp; &nbsp; dec_val = decodeURIComponent(value);&nbsp; &nbsp; &nbsp; final_value = dec_val.replace(/\+/g, ' ');&nbsp; &nbsp; &nbsp; dictionary[key] = final_value;&nbsp; &nbsp; }&nbsp; &nbsp; return (dictionary);&nbsp; };&nbsp; let i = 1;&nbsp; const obj = splitstring(string);&nbsp; const products = [];&nbsp; while (obj.hasOwnProperty(`product${i}`)) {&nbsp; &nbsp; products.push({&nbsp; &nbsp; &nbsp; [`product`]: obj[`product${i}`],&nbsp; &nbsp; &nbsp; [`productprice`]: obj[`productprice${i}`],&nbsp; &nbsp; &nbsp; [`productqty`]: obj[`product${i}qty`]&nbsp; &nbsp; });&nbsp; &nbsp; delete obj[`product${i}`];&nbsp; &nbsp; delete obj[`productprice${i}`];&nbsp; &nbsp; delete obj[`product${i}qty`];&nbsp; &nbsp; ++i;&nbsp; }&nbsp; return [obj, products];}console.log(process(string));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript