1

How to manipulate this object to URL query parameter.The example the the query parameter should be

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

Kallol Pratim
  • 56
  • 1
  • 9
  • 1
    can you add an example of the object – Gerardo BLANCO Jun 05 '18 at 12:11
  • 2
    You should utilize POST request type instead. Set request type to "application/json" and send the JSON objects as the request body payload instead of sending the data within the url. – SadmirD Jun 05 '18 at 12:13
  • You could just loop through each value of the object with a foreach loop and concat all of it to a string. If you know js, you know how to build it yourself. And you can't declare `citites` twice, use something as a comma seperator to define more values or something like that – Nebulosar Jun 05 '18 at 12:13
  • here's the object { "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 } – Kallol Pratim Jun 05 '18 at 12:18
  • Check this answer: https://stackoverflow.com/a/1714899/182474 – Gabor Garami Jun 05 '18 at 12:20
  • this is probably where graphql has advantages over using REST – Denis Tsoi Jun 05 '18 at 12:20

5 Answers5

1

Here is the code to convert any json no matter how deep it is into query params:

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);

I hope this solves your issue.

prolific
  • 765
  • 1
  • 6
  • 23
0
  1. You can try using Post Request
  2. Send a JSON String using JSON.Parse() and JSON.stringify() Convert your params array to JSON String and send that as a single query param. Decode the query string param (i.e JSON string)

Adding Example

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);

Output "%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], advocates: Array [Object { key: "7195", label: "kallol saikia" }], cities: Array [Object { key: 390, label: "Delhi" }, Object { key: 6, label: "Mumbai" }], checkbox-filed: true, checkbox-active: true }

vCillusion
  • 1,749
  • 20
  • 33
  • can you give me an example? I just want an function which return these data as URL parameter like below `advocates=7195&categories=25&checkbox-active=true&checkbox-close=undefined&checkbox-filed=true&checkbox-notFiled=undefined&cities=Delhi&cities=mumbai` – Kallol Pratim Jun 05 '18 at 12:22
  • Added the example – vCillusion Jun 05 '18 at 12:39
0

Maybe:

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);
madflow
  • 7,718
  • 3
  • 39
  • 54
0

Here is an example I just made: https://jsfiddle.net/BrandonQDixon/surwf7gd

The script below will loop through the keys of an object and convert them to GET style parameters, which is what your request looks like. I made it a function so you can directly call it on an object.

This will also work recursively, if your object has nested objects, but understand that if nested objects have some of the same keys (or there are duplicates in general), they will both be added to the string.

/**
  * 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;
}
Brandon Dixon
  • 1,036
  • 9
  • 16
0

This algorithm will work. Just with caution, if you change the object structure, this might break

Hope this helps :>

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 +  '&';
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35