-1

I am trying to convert the parameters from my URL (Example 1) to a JSON Object that looks like Example 2. Unfortunately when I use JSON.stringify() it converts it to Example 3. Can anyone please point me in the right direction for splitting this? I am not sure how to get the keys out.

Example 1 - Input

food=apple,banana,peach&store=walmart&customer=John

Example 2 - Desired Output

{"food": ["apple", "banana", "peach"], "store":"walmart", "customer":"John"}

Example 3 - Current Ouput

{"food=apple,banana,peach", "store=walmart", "customer=John"}

Edits:

Forgot "" in food list

What I tried

data = "food=apple,banana,peach&store=walmart&customer=John";
data = JSON.stringify(data);
Zac Warham
  • 158
  • 11
  • 1
    Your desired output is invalid JSON. If that's really exactly the output you want, this is definitely an X/Y problem. You sure you don't want the array items as strings, enclosed in `"`s? – CertainPerformance Sep 27 '19 at 06:47
  • As @CertainPerformance said, your desired output is not a JSON Object. Please provide an correct output *and* an example of what you tried – Weedoze Sep 27 '19 at 06:49
  • Yes I forgot to put the " " was a bit rushed submitting this – Zac Warham Sep 27 '19 at 16:13

1 Answers1

0

Using split, split the string appropriately and insert values in the object

var str = 'food=apple,banana,peach&store=walmart&customer=John';
var arr = str.split('&')
var obj = {};
for (let i = 0; i < arr.length; i++) {
var x = arr[i].split('=')
  if (i == 0) {
    obj[x[0]] = [];
    x[1].split(',').forEach(function(y) {
      obj[x[0]].push(y)
    })
  } else
    obj[x[0]] = x[1]
}
console.log(obj)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • 1
    You can use [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) instead of manually splitting – adiga Sep 27 '19 at 06:55