我的节点应用程序接收以下格式的一系列字符串"a=x b=y c=z"(即包含多个空格分隔对的字符串key=value)。
将此类字符串转换为以下形式的 JSON 对象的最简洁方法是什么{a: x, b: y, c: z}?
我打赌有一个单行解决方案,但还没有找到它。
谢谢。
Joh*_*pit 10
一种方法是将 a 替换为 a ,,将 an=替换为 a ::
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要在键和值周围加上引号:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
Run Code Online (Sandbox Code Playgroud)
JSON.parse()如果你需要的话。
示例输出:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16262 次 |
| 最近记录: |