Is there any native function to convert json to url parameters?

后端 未结 11 1879
再見小時候
再見小時候 2020-11-29 22:00

I need convert json object to url form like: \"parameter=12&asd=1\"

I done with this:

        var data = {
            \'action\':\'actualiza_res         


        
11条回答
  •  执笔经年
    2020-11-29 22:27

    But i wonder if there any function in javascript

    Nothing prewritten in the core.

    or json to do this?

    JSON is a data format. It doesn't have functions at all.


    This is a relatively trivial problem to solve though, at least for flat data structures.

    Don't encode the objects as JSON, then:

    function obj_to_query(obj) {
        var parts = [];
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
            }
        }
        return "?" + parts.join('&');
    }
    
    alert(obj_to_query({
        'action': 'actualiza_resultado',
        'postID': 1,
        'gl': 2,
        'gl2': 3
    }));  
    

    There isn't a standard way to encode complex data structures (e.g. with nested objects or arrays). It wouldn't be difficult to extend this to emulate the PHP method (of having square brackets in field names) or similar though.

提交回复
热议问题