【问题标题】:How to stringify an Object which includes objects of array?如何对包含数组对象的对象进行字符串化?
【发布时间】:2018-06-05 12:10:06
【问题描述】:

如何操作这个对象到URL查询参数。查询参数的例子应该是

advocates=7195&categories=25&checkbox-active=true&checkbox-close=undefined&checkbox-filed=true&checkbox-notFiled=undefined&cities=Delhi&cities=mumbai

【问题讨论】:

  • 能不能加个对象的例子
  • 您应该改用 POST 请求类型。将请求类型设置为“application/json”,并将 JSON 对象作为请求正文负载发送,而不是在 url 中发送数据。
  • 您可以使用 foreach 循环遍历对象的每个值,并将其全部连接到一个字符串中。如果你了解 js,你就知道如何自己构建它。而且你不能两次声明citites,使用一些东西作为逗号分隔符来定义更多的值或类似的东西
  • 这里是对象 { "stage": 50, "categories": [ 25, 23, 28 ], "advocates": [ { "key": "7195", "label": "kallol saikia" } ], "cities": [ { "key": 390, "label": "Delhi" }, { "key": 6, "label": "Mumbai" } ], "checkbox-filed": true , "复选框激活": true }
  • 查看这个答案:stackoverflow.com/a/1714899/182474

标签: javascript reactjs query-string


【解决方案1】:

以下是将任何 json 转换为查询参数的代码,无论它有多深:

var o = {
  "stage": 50,
  "categories": [25, 23, 28],
  "advocates": [{
    "key": "7195",
    "label": "kallol saikia"
  }],
  "cities": [{
    "key": 390,
    "label": "Delhi"
  }, {
    "key": 6,
    "label": "Mumbai"
  }],
  "checkbox-filed": true,
  "checkbox-active": true
}

function getParams(key, value) {
  var queries = [];
  var newKey;

  if (Array.isArray(value)) {
    for (var i = 0; i < value.length; i++) {
      newKey = key + "[" + i + "]";
      queries = queries.concat(getParams(newKey, value[i]));
    }
  } else if (value && typeof value === 'object' && value.constructor === Object) {
    for (var prop in value) {
      if (value.hasOwnProperty(prop)) {
        newKey = key ? key + "[" + prop + "]" : prop;
        queries = queries.concat(getParams(newKey, value[prop]));
      }
    }
  } else {
    queries.push(key + "=" + value);
  }

  return queries;
}

var query = getParams("", o).join("&");
console.log(query);

希望这能解决您的问题。

【讨论】:

    【解决方案2】:

    也许:

    var o = {
      'advocates': [{
        key: 1
      }],
      'checkbox-active': true
    };
    
    var query = Object.keys(o).map(function(i) {
      var val;
      if (Array.isArray(o[i])) {
        val = o[i][0].key;
      } else {
        val = o[i];
      }
      return i + '=' + val;
    }).join('&');
    
    console.log(query);
    

    【讨论】:

      【解决方案3】:
      1. 您可以尝试使用Post请求
      2. 使用 JSON.Parse()JSON.stringify() 发送 JSON 字符串 将您的参数数组转换为 JSON 字符串并将其作为单个查询参数发送。 解码查询字符串参数(即 JSON 字符串)

      添加示例

      var jsonString = JSON.stringify({
          "stage": 50,
          "categories": [25, 23, 28],
          "advocates": [{
              "key": "7195",
              "label": "kallol saikia"
          }],
          "cities": [{
              "key": 390,
              "label": "Delhi"
          }, {
              "key": 6,
              "label": "Mumbai"
          }],
          "checkbox-filed": true,
          "checkbox-active": true
      });
      // Pass down the Encoded Json 
      var encodedJson = encodeURI(jsonString); 
      console.log(encodedJson);
      // Decode Json
      var decodedJson = decodeURI(encodedJson);
      var decodedObject = JSON.parse(decodedJson);
      console.log(decodedObject);
      

      输出 "%7B%22stage%22:50,%22categories%22:%5B25,23,28%5D,%22advocates%22:%5B%7B%22key%22:%227195%22,%22label%22:%22kallol %20saikia%22%7D%5D,%22cities%22:%5B%7B%22key%22:390,%22label%22:%22Delhi%22%7D,%7B%22key%22:6,%22label%22 :%22Mumbai%22%7D%5D,%22checkbox-filed%22:true,%22checkbox-active%22:true%7D"

      Object { stage: 50, categories: Array [25, 23, 28], 倡导者: Array [Object { key: "7195", label: "kallol saikia" }], city: Array [Object { key: 390 , label: "Delhi" }, Object { key: 6, label: "Mumbai" }], checkbox-filed: true, checkbox-active: true }

      【讨论】:

      • 你能举个例子吗?我只想要一个将这些数据作为 URL 参数返回的函数,如下所示advocates=7195&amp;categories=25&amp;checkbox-active=true&amp;checkbox-close=undefined&amp;checkbox-filed=true&amp;checkbox-notFiled=undefined&amp;cities=Delhi&amp;cities=mumbai
      • 添加示例
      【解决方案4】:

      这个算法会起作用。请注意,如果您更改对象结构,这可能会中断

      希望这会有所帮助:>

      var obj = {
        "stage": 50,
        "categories": [25, 23, 28],
        "advocates": [{
          "key": "7195",
          "label": "kallol saikia"
        }],
        "cities": [{
          "key": 390,
          "label": "Delhi"
        }, {
          "key": 6,
          "label": "Mumbai"
        }],
        "checkbox-filed": true,
        "checkbox-active": true
      }
      
      
      let str = 'advocates=' + obj.advocates[0].key +
                '&categories=' + obj.categories[0] + 
                'checkbox-active=' + obj['checkbox-active'] + 
                'checkbox-close=' + obj['checkbox-close'] + 
                'checkbox-filed=' + obj['checkbox-filed'] + 
                'checkbox-notFiled=' + obj['checkbox-notFiled'];
      
      obj.cities.forEach(city=>str+= 'cities=' + city.label + '&')
      str = str.substring(0,str.length-1)      
      console.log(str)
      
       
      advocates=7195&
      categories=25&
      checkbox-active=true&
      checkbox-close=undefined&
      checkbox-filed=true&
      checkbox-notFiled=undefined&
      cities=Delhi&
      cities=mumbai
      
      
      `${key}${i>0?'&':''}${val[0]}=${val[1]}`, ""
          'advocates':
           'checkbox-active':
           'checkbox-close':
           'checkbox-filed':
           'checkbox-notFiled':
            arrStr += key[0] + '=';
            arrStr += key[1][0].key +  '&';

      【讨论】:

        【解决方案5】:

        这是我刚刚做的一个例子:https://jsfiddle.net/BrandonQDixon/surwf7gd

        下面的脚本将遍历对象的键并将它们转换为 GET 样式参数,这就是您的请求的样子。我把它做成了一个函数,所以你可以直接在一个对象上调用它。

        这也将递归地工作,如果您的对象有嵌套对象,但要明白,如果嵌套对象有一些相同的键(或者通常有重复项),它们都会被添加到字符串中。

        /**
          * This will turn an object into a GET style parameter
          * This scans recursively if 2nd param is set to true, but "flattens" every property into one string, so this may cause some overriding
          * This will encode the keys and values if 3rd param is set to true
          */
        function paramatize(obj,recursive = true,encode = true) {
          let str = "";
        
          let len = Object.keys(obj).length
          let i = 0;
          for (let key in obj) {
        
            i++;
            if (typeof obj[key] === 'object' && recursive) {
              str += paramatize(obj[key]);
            } else {
              let nKey = (encode)?encodeURIComponent(key):key;
              let nValue = (encode)?encodeURIComponent(obj[key]):obj[key];
        
              str += nKey+"="+nValue;
            }
        
            if (i < len) {
              str += "&";
            }
          }
        
          return str;
        }
        

        【讨论】:

          猜你喜欢
          • 2012-01-20
          • 1970-01-01
          • 2016-11-10
          • 2019-06-06
          • 2020-09-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-14
          相关资源
          最近更新 更多