且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将具有key = value对的字符串解析为JSON

更新时间:2022-05-05 23:03:43

一种方法是将替换为,,将=替换为::

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"}