Vignesh
Vignesh

Reputation: 45

Convert String of certain format to JSON in javascript

I have a string of the format

 var str = "{key1=value1, Key2=value2}"

I need to convert this into a json object to be able to iterate through it.

Any suggestions on how this can be done? there can be any number of keys

Upvotes: 0

Views: 522

Answers (1)

You need first to "JSONize" this string you are getting so it can be converted to a JavaScript object using the JSON class. My guess, if the string has always this format ({key=value, ...}), is that you could parse it first like this:

var parsedString = yourString.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"')

This way, from this: "{key1=value1, Key2=value2}" you get this: '{"key1":"value1", "Key2":"value2"}'.

Then, as someone suggested, just use JSON.parse(parsedString) to get your JS object.

Upvotes: 2

Related Questions