拆分以'='符号分隔的以管道分隔的键值对 [英] Split a pipe delimited key-value pair separated by '=' symbol
本文介绍了拆分以'='符号分隔的以管道分隔的键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们收到一个输入参数值作为管道分隔的键值对,用 =
符号分隔。例如:
We are receiving an input parameter value as a pipe-delimited key-value pair, separated with =
symbols. For example:
"|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|"
因此格式为: | KEY = VALUE | KEY_2 = VALUE_2 |。 ... | KEY_n = VALUE_n |
我需要将其拆分为JSON对象。所以,我的目标应该是:
I need to split it into a JSON object. So, my object should be :
{
'User':'0101',
'Name':'ImNewUser',
'IsAdmin':'0',
'RefId'='23ae2123cd223bf235'
}
最好的方法是什么,因为有多种选择:
What will be best way to go, since there are multiple options:
- I可以使用
|
拆分,并再次使用=
拆分每个元素。 - 我可以依赖正则表达式并进行字符串替换。
- 将其拆分为
=
删除尾随|
符号并将两个
不同的数组与索引相关联。
- I can use split with
|
and again on each element split with=
. - I can depend on regular expression and do string replace.
- Split it with
=
remove trailing|
symbol and associate two different arrays with indexes.
任何人都可以告诉我最好/最多在JavaScript中这样做的有效方法(在Node.js中编程)?
Can anyone tell me the best/most efficient way of doing this in JavaScript (programming in Node.js)?
推荐答案
第一个听起来不错:
var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
var result = {};
str.split('|').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
这篇关于拆分以'='符号分隔的以管道分隔的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文