How to encode a string as key value pairs

I want to encode a string as key / value pairs. The data is passed to me as a string (I use the jstorage plugin).

I tried to split the string as an array, but it does not return the correct key / values.

Example

"color":"#000000", "font":"12px", "background":"#ffffff", 
+4
source share
2 answers

If you always get such a string, that is, keys and values โ€‹โ€‹in double quotes, you can add {...} to the string and parse it as JSON :

 // remove trailing comma, it not valid JSON var obj = JSON.parse('{' + str.replace(/,\s*$/, '') + '}'); 

If not, splitting a string is also easy, assuming that , and : cannot occur in keys or values:

 var obj = {}, parts = str.replace(/^\s+|,\s*$/g, '').split(','); for(var i = 0, len = parts.length; i < len; i++) { var match = parts[i].match(/^\s*"?([^":]*)"?\s*:\s*"?([^"]*)\s*$/); obj[match[1]] = match[2]; } 
+7
source

You need to evaluate it in a JavaScript object. If you trust the source or can check the content, you can do this:

 s = document.createElement('script') s.type='text/javascript'; s.innerHTML = 'var data = {'+ text + '}'; document.getElementsByTagName('head')[0].appendChild(s); 
0
source

Source: https://habr.com/ru/post/1398909/


All Articles