将具有key = value对的字符串解析为JSON [英] Parse string having key=value pairs as JSON
本文介绍了将具有key = value对的字符串解析为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的节点应用接收到一系列格式为"a=x b=y c=z"
的字符串(即,包含几个以空格分隔的key=value
对的字符串).
My node app receives a series of strings in the format "a=x b=y c=z"
(i.e. a string containing several space-separated key=value
pairs).
将这样的字符串转换为形式为{a: x, b: y, c: z}
的JSON对象的最巧妙的方法是什么?
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}
?
我敢打赌,这里有一种解决方案,但还没有找到.
I'm betting that there's a one-line solution, but haven't managed to find it yet.
谢谢.
推荐答案
一种方法是将替换为
,
,将=
替换为:
:
One way would be to replace the with a
,
and an =
with a :
:
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
或者如果您需要在键和值两边加上引号:
Or if you need quotes around the keys and values:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
JSON.parse()
,如果需要的话.
JSON.parse()
it if you need.
示例输出:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
这篇关于将具有key = value对的字符串解析为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文