简体   繁体   English

如何将键/值对String转换为JSON对象?

[英]How to Convert key/value pair String to a JSON object?

How can I covert key=value pair string to json object 如何将key = value对字符串隐蔽到json对象

input : 输入:

test = one
testTwo = two

Output should be json object 输出应为json对象

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

Is input a string? input字符串吗? 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. 您可以先将\\n拆分为一个键/值对数组,然后将每个对拆分为= ,以获取一个键和值数组。

 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); 

最安全的方法是JSON.parse(string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM