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

后端 未结 11 1835
再見小時候
再見小時候 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.

    0 讨论(0)
  • Based on georg's answer, but also adding ? before the string and using ES6:

      const query = !params ? '': Object.keys(params).map((k, idx) => {
        let prefix = '';
        if (idx === 0) {
          prefix = '?';
        }
        return prefix + encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
      }).join('&');
    
    0 讨论(0)
  • 2020-11-29 22:31

    Something I find nicely looking in ES6:

    function urlfy(obj) {
        return Object
            .keys(obj)
            .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
            .join('&');
    }
    

    Later update (same thing, maybe a bit cleaner):

    const urlfy = obj => Object
        .keys(obj)
        .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
        .join('&');
    
    0 讨论(0)
  • 2020-11-29 22:33

    I made an implementation that support nested objects and arrays i.e.

    var data = {
        users: [
        {
          "name": "jeff",
          "tasks": [
            "Do one thing",
            "Do second thing"
          ]
        },
        {
          "name": "rick",
          "tasks": [
            "Never gonna give you up",
            "Never gonna let you down"
          ]
        }
      ]
    }
    

    Will be:

    users[0][name]=jeff&users[0][tasks][0]=Do%20one%20thing&users[0][tasks][1]=Do%20second%20thing&users[1][name]=rick&users[1][tasks][0]=Never%20gonna%20give%20you%20up&users[1][tasks][1]=Never%20gonna%20let%20you%20down
    

    So, here's the implementation:

    var isObj = function(a) {
      if ((!!a) && (a.constructor === Object)) {
        return true;
      }
      return false;
    };
    var _st = function(z, g) {
      return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
    };
    var fromObject = function(params, skipobjects, prefix) {
      if (skipobjects === void 0) {
        skipobjects = false;
      }
      if (prefix === void 0) {
        prefix = "";
      }
      var result = "";
      if (typeof(params) != "object") {
        return prefix + "=" + encodeURIComponent(params) + "&";
      }
      for (var param in params) {
        var c = "" + prefix + _st(param, prefix);
        if (isObj(params[param]) && !skipobjects) {
          result += fromObject(params[param], false, "" + c);
        } else if (Array.isArray(params[param]) && !skipobjects) {
          params[param].forEach(function(item, ind) {
            result += fromObject(item, false, c + "[" + ind + "]");
          });
        } else {
          result += c + "=" + encodeURIComponent(params[param]) + "&";
        }
      }
      return result;
    };
    
    var data = {
      users: [{
          "name": "jeff",
          "tasks": [
            "Do one thing",
            "Do second thing"
          ]
        },
        {
          "name": "rick",
          "tasks": [
            "Never gonna give you up",
            "Never gonna let you down"
          ]
        }
      ]
    }
    
    document.write(fromObject(data));

    0 讨论(0)
  • 2020-11-29 22:34

    Like @georg said, you can use JQuery.param for flat objects.

    If you need to process complex objects, you can use JsonUri, a python package that does just that. There is JavaScript library for it as well

    Disclaimer: I am the author of JSONURI

    Edit: I learned much later that you can also just base64 encode your payload - most languages as support for base64 encoding/decoding

    Example

    x = {name: 'Petter', age: 47, places: ['Mozambique', 'Zimbabwe']}
    stringRep = JSON.stringify(x)
    encoded = window.btoa(stringRep)
    

    Gives you eyJuYW1lIjoiUGV0dGVyIiwiYWdlIjo0NywicGxhY2VzIjpbIk1vemFtYmlxdWUiLCJaaW1iYWJ3ZSJdfQ==, which you can use as a uri parameter

    decoded = window.atob(encoded)
    originalX = JSON.parse(decoded)
    

    Needless to say, it comes with its own caveats

    0 讨论(0)
  • 2020-11-29 22:39

    You don't need to serialize this object literal.

    Better approach is something like:

    function getAsUriParameters(data) {
       var url = '';
       for (var prop in data) {
          url += encodeURIComponent(prop) + '=' + 
              encodeURIComponent(data[prop]) + '&';
       }
       return url.substring(0, url.length - 1)
    }
    getAsUriParameters(data); //"action=actualiza_resultado&postID=1&gl=2&gl2=3"
    
    0 讨论(0)
提交回复
热议问题