How to convert a key / value pair string into a JSON object?

advertisements

How can I covert key=value pair string to json object

input :

test = one
testTwo = two

Output should be json object

  "test":"one","testTwo":"two"


Is input a string? You could first split it by \n to get an array of key/value-pairs, and then split each pair by =, to get an array of the key and the value.

var input = `test = one
testTwo = two
testThree = three
testFour = four`;

var output = input.split('\n').reduce(function(o,pair) {
   pair = pair.split(' = ');
   return o[pair[0]] = pair[1], o;
}, {});

console.log(output);