-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);
3
  • 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? Commented Sep 27, 2019 at 6:47
  • As @CertainPerformance said, your desired output is not a JSON Object. Please provide an correct output and an example of what you tried Commented Sep 27, 2019 at 6:49
  • Yes I forgot to put the " " was a bit rushed submitting this Commented Sep 27, 2019 at 16:13

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

You can use URLSearchParams instead of manually splitting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.