开发者

Convert string into storable variable names and values (as strings, and objects)

开发者 https://www.devze.com 2023-03-15 18:16 出处:网络
2015 Edit Don\'t do this. Be a good person and Just Use JSON.parse() :) I am trying to take a string which contains variables and values in a javascript-like syntax, and store them in a global obje

2015 Edit Don't do this. Be a good person and Just Use JSON.parse() :)

I am trying to take a string which contains variables and values in a javascript-like syntax, and store them in a global object (gv). My issue is just with the parsing of the string.

String (everything inside the <div>):

<div id="gv">       
    variableName = "variableValue,NoSpacesThough";
    portal = "TheCakeIsALie";
&开发者_运维问答lt;/div>

Script (parses string above, places values into global object):

var s = (document.getElementById("gv").innerHTML).split(';');
for (var i = 0; i < s.length; i++) {
    if (s[i] !== "\n" || "") {
        s[i] = s[i].replace(/^\s*/gm, "");
        var varName = s[i].substr(0, s[i].indexOf('=') - 1),
            varValue = (s[i].substr((s[i].indexOf('"') + 1), s[i].length)).replace('"', "");
        gv[varName] = varValue;
    }
}

Result:

console.log(gv.variableName); //returns: variableValue,NoSpacesThough
console.log(gv.portal); //returns: TheCakeIsALie

Q: How can I modify this script to correctly store these variables:

exampleVariable = { name: "string with spaces", cake:lie };
variableName = "variableValue,NoSpacesThough";    
portal = "The Cake Is A Lie";

The directly above has an object containing: A string with spaces (and "), a reference

Thanks.


Four options / thoughts / suggestions:

1. Use JSON

If you're in control of the source format, I'd recommend using JSON rather than rolling your own. Details on that page. JSON is now part of the ECMAScript (JavaScript) standard with standard methods for creating JSON strings from object graphs and vice-versa. With your example:

exampleVariable = { name: "string with spaces", cake:lie };
variableName = "variableValue,NoSpacesThough";    
portal = "The Cake Is A Lie";

here's what the JSON equivalent would look like:

{  
    "exampleVariable": { name: "string with spaces", cake:lie },
    "variableName": "variableValue,NoSpacesThough",
    "portal": "The Cake Is A Lie"
}

As you can see, the only differences are:

  1. You wrap the entire thing in curly braces ({}).
  2. You put the "variable" names (property names) in double quotes.
  3. You use a colon rather than an equal sign after the property name.
  4. You use a comma rather than a semicolon to separate properties (just as in the object literal you have on your exampleVariable line).
  5. You ensure that any string values use double, rather than single, quotes (JavaScript allows either; JSON is more restrictive). Your example uses double quotes, but I mention it just in case...

2. Pre-process it into JSON with regular expressions

If you're not in control of the source format, but it's exactly as you've shown, you could reformat it as JSON fairly easily via regular expressions, and then deserialize it with the JSON stuff. But if the format is more complicated than you've quoted, that starts getting hairy very quickly.

Here's an example (live copy) of transforming what you've quoted to JSON:

function transformToJSON(str) {
  var rexSplit = /\r?\n/g,
      rexTransform = /^\s*([a-zA-Z0-9_]+)\s*=\s*(.+);\s*$/g,
      rexAllWhite = /\s+/g,
      lines,
      index,
      line;

  lines = str.split(rexSplit);
  index = 0;
  while (index < lines.length) {
    line = lines[index];
    if (line.replace(rexAllWhite, '').length === 0) {
      // Blank line, remove it
      lines.splice(index, 1);
    }
    else {
      // Transform it
      lines[index] = line.replace(rexTransform, '"$1": $2');
      ++index;
    }
  }
  result = "{\n" + lines.join(",\n") + "\n}";
  return result;
}

...but beware as, again, that relies on the format being exactly as you showed, and in particular it relies on each value being on a single line and any string values being in double quotes (a requirement of JSON). You'll probably need to handle complexities the above doesn't handle, but you can't do it with things like your first line var s = (document.getElementById("gv").innerHTML).split(';');, which will break lines on ; regardless of whether the ; is within quotes...

3. Actually parse it by modifying a JSON parser to support your format

If you can't change the format, and it's less precise than the examples you've quoted, you'll have to get into actual parsing; there are no shortcuts (well, no reliable ones). Actually parsing JavaScript literals (I'm assuming there are not expressions in your data, other than the assignment expression of course) isn't that bad. You could probably take a JSON parser and modify it to your needs, since it will already have nearly all the logic for literals. There are two on Crockford's github page (Crockford being the inventer of JSON), one using recursive descent and another using a state machine. Take your choice and start hacking.

4. The evil eval

I suppose I should mention eval here, although I don't recommend you use it. eval runs arbitrary JavaScript code from a string. But because it runs any code you give it, it's not a good choice for deserializing things like this, and any free variables (like the ones you've quoted) would end up being globals. Really very ugly, I mostly mention it in order to say: Don't use it. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消