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"
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"
Share
Improve this question
edited Sep 2, 2016 at 6:15
Subodh Joshi
13.6k36 gold badges119 silver badges209 bronze badges
asked Sep 2, 2016 at 5:12
dileep Hdileep H
3551 gold badge3 silver badges9 bronze badges
1
- 1 Please try doing this on your own. If you fail, research why you are failing and correct your code. If you still fail, show the code which is failing and the measures you took to correct it and how others can reproduce your problem. Maybe then someone can help you. – Ishita Sinha Commented Sep 2, 2016 at 6:57
2 Answers
Reset to default 8Is 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);
The safest way to do it is JSON.parse(string)