Notes: This parser is more lenient than a standard JavaScript parser, accepting unquoted keys with special characters and accepting keys without a value. It also silently ignores errors such as a missing key (the value will be skipped). If a value expression contains unquoted spaces, they may be stripped in the result.
-
Simple object literals
parseObjectLiteral("a: 1, b: 2, \"quotedKey\": 3, 'aposQuotedKey': 4");
[ ["a","1"], ["b","2"], ["quotedKey","3"], ["aposQuotedKey","4"] ]
-
With enclosing braces
parseObjectLiteral("{a: 1}");
[ ["a","1"] ]
-
String values
parseObjectLiteral(
"a: \"comma, colon: brace{ bracket[ apos' escapedQuot\\\" end\","
+ "b: 'escapedApos\\' brace} bracket] quot\"'");
[
["a","\"comma, colon: brace{ bracket[ apos' escapedQuot\\\" end\""],
["b","'escapedApos\\' brace} bracket] quot\"'"]
]
-
Values with objects, arrays, function literals, and regular expressions
parseObjectLiteral(
"myObject:{someChild:{}, someChildArray:[1,2,3], \"quotedChildProp\":'string value'},\n"
+ "someFn:function(a,b,c){var regex=/}/g;var str='/})({';return{};},"
+ "myArray:[{}, function(){}, \"my'Str\", 'my\"Str']"
);
[
["myObject","{someChild:{},someChildArray:[1,2,3],\"quotedChildProp\":'string value'}"],
["someFn","function(a,b,c){var regex=/}/g;var str='/})({';return{};}"],
["myArray","[{},function(){},\"my'Str\",'my\"Str']"]
]
-
Keys with special characters
parseObjectLiteral("a.b: 1, b+c: 2, c=d: 3, d_e: 4");
[ ["a.b","1"], ["b+c","2"], ["c=d","3"], ["d_e","4"] ]
-
Keys without values, values without keys, etc.
parseObjectLiteral("keyonly, 'key:quoted', key:, {nokey: 4}");
[ ["keyonly",undefined], ["key:quoted",undefined], ["key",undefined], [undefined,"{nokey:4}"] ]