Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string having key=value pairs as JSON

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

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.

Thanks.

like image 734
drmrbrewer Avatar asked Jan 08 '23 17:01

drmrbrewer


1 Answers

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() it if you need.

Sample output:

str:      a=x b=y c=z
jsonStr:  {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
like image 167
6 revs Avatar answered Jan 15 '23 19:01

6 revs