简体   繁体   English

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

[英]How to convert json object containing object arrays into url encoded format

I am trying to convert json object to url encoded format but my json contains array objects so jQuery.param() function is not working. 我正在尝试将json对象转换为url编码格式,但是我的json包含数组对象,因此jQuery.param()函数无法正常工作。 please tell me how to achieve this. 请告诉我如何实现这一目标。 This is the json: 这是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"}
 ]
}

I suggest to pass the JSON data as a POST request but if you want to pass in URL use this : 我建议将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> 

I assume you are looking for a JavaScript solution, which runs in the browser ... 我假设您正在寻找一种JavaScript解决方案,该解决方案可以在浏览器中运行...

  1. You can convert any JavaScript object into a string via JSON.stringify 您可以通过JSON.stringify将任何JavaScript对象转换为字符串。
  2. You can url encode any string with the encodeURIComponent function 您可以使用encodeURIComponent函数对任何字符串进行URL编码

Example: 例:

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

This will give you: 这将为您提供:

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

Try this: 尝试这个:

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 码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM