admin管理员组文章数量:1327945
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)
本文标签: javascriptHow to Convert keyvalue pair String to a JSON objectStack Overflow
版权声明:本文标题:javascript - How to Convert keyvalue pair String to a JSON object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742224313a2435800.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论