如何将包含对象数组的json对象转换为url编码格式

时间:2018-06-20 09:56:26

标签: javascript jquery json typescript urlencode

我正在尝试将json对象转换为url编码格式,但是我的json包含数组对象,因此jQuery.param()函数无法正常工作。请告诉我如何实现这一目标。 这是json:

{"details":
 [
   {"product_name":"knee 
   cap","price":"123","quantity":"2","size":"small","color":"blue"}, 
   {"product_id":2,"product_name":"soft 
   pillow","price":"123","quantity":"2","size":"small","color":"blue"}
 ]
}

3 个答案:

答案 0 :(得分:0)

我建议将JSON数据作为POST请求传递,但是如果您要传递URL,请使用以下命令:

 var result = encodeURIComponent(JSON.stringify(object_to_be_serialised))

const params = {
  "details": [{
    "product_name": "knee cap",
    "price": "123",
    "quantity": "2",
    "size": "small",
    "color": "blue"
  }, {
    "product_id": 2,
    "product_name": "soft pillow",
    "price": "123",
    "quantity": "2",
    "size": "small",
    "color": "blue"
  }]
}

document.write(
  encodeURIComponent(JSON.stringify(params))
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

我假设您正在寻找一种JavaScript解决方案,该解决方案可以在浏览器中运行...

  1. 您可以通过JSON.stringify
  2. 将任何JavaScript对象转换为字符串。
  3. 您可以使用encodeURIComponent函数对任何字符串进行url编码

示例:

const json = {details: [{name: "foo"}, {name: "bar"}]};
const s = encodeURIComponent(JSON.stringify(json));
console.log(s);

这将为您提供:

%7B%22details%22%3A%5B%7B%22name%22%3A%22foo%22%7D%2C%7B%22name%22%3A%22bar%22%7D%5D%7D

答案 2 :(得分:-1)

尝试一下:

var l = {
  details: [
    {
      product_name: "kneecap",
      price: "123",
      quantity: "2",
      size: "small",
      color: "blue"
    },
    {
      product_id: 2,
      product_name: "soft pillow",
      price: "123",
      quantity: "2",
      size: "small",
      color: "blue"
    }
  ]
};

function encode(obj, prefix) {
  var str = [],
    p;
  for (p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p,
        v = obj[p];
      str.push(
        v !== null && typeof v === "object"
          ? encode(v, k)
          : encodeURIComponent(k) + "=" + encodeURIComponent(v)
      );
    }
  }
  return str.join("&");
}

console.log(encode(l));

codepen