-2

I have this string

_token=mRdKQDuJYgNSPW8ixwZ2pgnTDpek5GM3O5OptdbX&edit_saved_report=&start_date=2022-02-14&end_date=2022-02-14&timezone=US%2FEastern&dsp_id%5B%5D=&ssp_id%5B%5D=&pub_id%5B%5D=&deal_id%5B%5D=&agency_id%5B%5D=&brand_id%5B%5D=&deal_personnel%5B%5D=&deal_type%5B%5D=&device_type=&media_type=

how I can convert it to json using java script? I need it to be key -> value pairs and not as html

this is the soloution: let test2 = JSON.parse('{"' + sagidata.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Bastian
  • 1,089
  • 7
  • 25
  • 74
  • 3
    Does this answer your question? [How to convert URL parameters to a JavaScript object?](https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object) – Ivar Feb 15 '22 at 12:39
  • There no language named `java script` there is `java` or `javascript` at which one do you refer your question ? – Mister Jojo Feb 15 '22 at 12:40
  • 1
    `Object.fromEntries([...new URLSearchParams('_token=mRdKQDuJYgNSPW8ixwZ2pgnTDpek5GM3O5OptdbX&edit_saved_report=&start_date=2022-02-14&end_date=2022-02-14&timezone=US%2FEastern&dsp_id%5B%5D=&ssp_id%5B%5D=&pub_id%5B%5D=&deal_id%5B%5D=&agency_id%5B%5D=&brand_id%5B%5D=&deal_personnel%5B%5D=&deal_type%5B%5D=&device_type=&media_type=').entries()])` – Keith Feb 15 '22 at 12:46

1 Answers1

1

You can use String.split() method.

Working Demo :

let str = "_token=mRdKQDuJYgNSPW8ixwZ2pgnTDpek5GM3O5OptdbX&edit_saved_report=&start_date=2022-02-14&end_date=2022-02-14&timezone=US%2FEastern&dsp_id%5B%5D=&ssp_id%5B%5D=&pub_id%5B%5D=&deal_id%5B%5D=&agency_id%5B%5D=&brand_id%5B%5D=&deal_personnel%5B%5D=&deal_type%5B%5D=&device_type=&media_type=";

let obj = {};

str.split('&').forEach((elem) => {
    obj[elem.split('=')[0]] = elem.split('=')[1] 
});

console.log(obj);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • 1
    Why `forEach` instead of `reduce`? – jabaa Feb 15 '22 at 12:41
  • As we are not doing any manipulations in the elements. We are just going to assign a properties in an object. Hence, I used `forEach` over `map`. – Debug Diva Feb 15 '22 at 12:41
  • You could write `const obj = str.split('&').reduce((acc, elem) => ..., {})` – jabaa Feb 15 '22 at 12:45
  • Only problem here is that `timezone: "US/Eastern"` is not getting decoded correctly. or `dsp_id[]` etc. – Keith Feb 15 '22 at 12:50
  • `reduce` shouldn't be used as a panacea for all iteration issues. `forEach` is a solid solution. – Andy Feb 15 '22 at 12:51
  • this solved it: let test2 = JSON.parse('{"' + sagidata.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) }) – Bastian Feb 15 '22 at 14:05