javascript.netjint

Eval javascript object using jint


I'm using jint to parse javascript code, the following js codes work:

but this one fails:

{ a: 1}

with this error:

int.Parser.ParserException: Line 1: Unexpected token : at Jint.Parser.JavaScriptParser.ThrowError(Token token, String messageFormat, Object[] arguments) at Jint.Parser.JavaScriptParser.ThrowUnexpected(Token token) at Jint.Parser.JavaScriptParser.ConsumeSemicolon() at Jint.Parser.JavaScriptParser.ParseStatement() at Jint.Parser.JavaScriptParser.ParseStatement() at Jint.Parser.JavaScriptParser.ParseSourceElement() at Jint.Parser.JavaScriptParser.ParseStatementList() at Jint.Parser.JavaScriptParser.ParseBlock() at Jint.Parser.JavaScriptParser.ParseStatement() at Jint.Parser.JavaScriptParser.ParseSourceElement() at Jint.Parser.JavaScriptParser.ParseSourceElements() at Jint.Parser.JavaScriptParser.ParseProgram() at Jint.Parser.JavaScriptParser.Parse(String code, ParserOptions options) at Jint.Engine.Execute(String source)

I don't want to deserialize a JSON file, I want to execute a javascript object, I'd like to have something like:

{
  id: 'one',
  code: function() { console.log('hello'); }
}

I noticed that if I do this:

var x = {a: 1}
x

then it works, but I need it to be a javascript object in my scenario.

Is there a way to achieve this?


Solution

  • { a: 1} gets interpreted as a block statement rather than an object literal. The solution is to wrap it in parenthesis:

    ({ a: 1 })