将JSON对象的深层Javascript或jQuery转换为查询字符串

时间:2017-04-26 20:37:45

标签: javascript jquery json regex urlencode

我需要帮助解决jQuery的$ .param()缺陷问题,这个问题不够深入,而且它会留下一些更深层次的JSON,例如%5D等等上。

这不是PayEezy电子商务API的问题,但是他们的沙箱API需要一个如下所示的查询字符串:

https://api-cert.payeezy.com/v1/securitytokens?apikey=FAKEZdp9nJrKu46wX9evGNnRbGL38W6I&js_security_key=js-FAKE79a767d3fea1611ae66e1c6bfd2af8f879a767d3fea1&callback=respondPEZ&auth=true&ta_token=NOIW&type=FDToken&currency=USD&credit_card.cardholder_name=John+Doe&credit_card.card_number=4111111111111111&credit_card.exp_date=1218&credit_card.cvv=100&credit_card.type=visa&billing_address.street=&billing_address.city=&billing_address.state_province=&billing_address.zip_postal_code=&billing_address.country=&billing_address.email=&billing_address.phone.type=&billing_address.phone.number=

当你看到这一点时,我希望你注意billing_address.state而不是billing_address[state],而不是billing_address%5Bstate%5D。我需要PayEezy的特殊方式。

所以,我在Javascript中创建了这个JSON对象:

var o = {
    apikey: 'FAKEZdp9nJrKu46wX9evGNnRbGL38W6I',
    js_security_key: 'js-FAKE79a767d3fea1611ae66e1c6bfd2af8f879a767d3fea1',
    callback: 'respondPEZ',
    auth: true,
    ta_token: 'NOIW',
    type: 'FDToken',
    currency: 'USD',                
    credit_card: {
        type: 'visa',
        cardholder_name: 'John Doe',
        card_number: '4111111111111111',
        exp_date: '1218',
        cvv: '100'
    },
    billing_address: {
        street: undefined,
        city: undefined,
        state_province: undefined,
        zip_postal_code: undefined,
        country: undefined,
        email: undefined,
        phone: {
            type: undefined,
            number: undefined
        }
    }
};

现在,当你通过jQuery的$ .param()运行它时,你会得到一个与查询字符串不够接近的结果:

apikey=FAKEZdp9nJrKu46wX9evGNnRbGL38W6I&js_security_key=js-FAKE79a767d3fea1611ae66e1c6bfd2af8f879a767d3fea1&callback=respondPEZ&auth=true&ta_token=NOIW&type=FDToken&currency=USD&credit_card%5Btype%5D=visa&credit_card%5Bcardholder_name%5D=John+Doe&credit_card%5Bcard_number%5D=4111111111111111&credit_card%5Bexp_date%5D=12%2F18&credit_card%5Bcvv%5D=100&billing_address%5Bstreet%5D=&billing_address%5Bcity%5D=&billing_address%5Bstate_province%5D=&billing_address%5Bzip_postal_code%5D=&billing_address%5Bcountry%5D=&billing_address%5Bemail%5D=&billing_address%5Bphone%5D%5Btype%5D=&billing_address%5Bphone%5D%5Bnumber%5D=

查看%5D%5B的人?这些都是不受欢迎的,而不是PayEezy在API中想要的。

所以,我设法通过这样做来接近解决问题:

var s = decodeURIComponent($.param(o,false));

但后来发现我可以通过这样做来解决它:

var s = decodeURIComponent($.param(o,false))
    .replace(/\]\=/g,'=')
    .replace(/\]\[/g,'.')
    .replace(/\[/g,'.');

我的问题是 - 是否有更精彩的方法将对象嵌入的JSON对象转换为更友好的URL查询字符串,该字符串不包含方括号并包含点符号,以及也许在比我定居的正则表达式替换技术更少的代码行中?例如,jQuery或Javascript中是否已经存在一些函数,当它们组合在一起时,处理得相当不错,我不知道?

1 个答案:

答案 0 :(得分:0)

我制作了自己的递归序列化程序。希望它按要求工作。

该函数将循环遍历对象的所有属性。如果值是一个对象,它将调用自身并传入"breadcrum"breadcrum只是一条"路径"函数已经到达的位置的属性。例如,如果我们在结算地址中查看电话类型,则传递给该功能的breadcrum将为billing_address.phone.

如果该值不是对象,则它只是将其自身附加到breadcrum并再次将其自身附加到查询字符串。

如果值为undefined,我只是将其设置为空字符串。



var o = {
    apikey: 'FAKEZdp9nJrKu46wX9evGNnRbGL38W6I',
    js_security_key: 'js-FAKE79a767d3fea1611ae66e1c6bfd2af8f879a767d3fea1',
    callback: 'respondPEZ',
    auth: true,
    ta_token: 'NOIW',
    type: 'FDToken',
    currency: 'USD',                
    credit_card: {
        type: 'visa',
        cardholder_name: 'John Doe',
        card_number: '4111111111111111',
        exp_date: '1218',
        cvv: '100'
    },
    billing_address: {
        street: undefined,
        city: undefined,
        state_province: undefined,
        zip_postal_code: undefined,
        country: undefined,
        email: undefined,
        phone: {
            type: undefined,
            number: undefined
        }
    }
};

function convertToQueryString(object, currentBreadcrum = '') {
    var queryString = '';
    
    for (var property in object) {
        var potentialObject = object[property];
        
        if (typeof potentialObject === 'undefined') {
            potentialObject = '';
        } // set undefined values to an empty string
        
        if (typeof potentialObject === 'object') {
            queryString += convertToQueryString(potentialObject, currentBreadcrum + property + '.');
        } else {
            if (currentBreadcrum === '' && queryString === '') { // don't prepend an '&' if it's the first item in the query string
                queryString += currentBreadcrum + property + '=' + potentialObject;
            } else {
                queryString += '&' + currentBreadcrum + property + '=' + potentialObject;
            }
        }
    }
    
    return queryString;
}

console.log(convertToQueryString(o));