title: How do I return a JSON string from an Eval call to JScript.NET?
body: <p>I am trying to use JScript.NET to do dynamic code evaluation.  I have a simple JScript.NET eval method that handles that:</p>
  
  <pre><code>public static object Eval(string javascript) {
    return Microsoft.JScript.Eval.JScriptEvaluate(javascript, Microsoft.JScript.Vsa.VsaEngine.CreateEngine());
  }
  </code></pre>
  
  <p>I would like to be able to pass objects into the Eval and get them back out again, and I'd like to do that via JSON.  I can pass objects from C# into my JScript without any problem by serializing them using JSON.NET.  What I'm having trouble doing is getting JSON back <strong>out</strong> from my javascript program into my C# caller.  When I return a object, what I get back is a JSObject (<a href="http://msdn.microsoft.com/en-us/library/microsoft.jscript.jsobject.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.jscript.jsobject.aspx</a>).  I apparently cannot JSON.stringify() in JScript.NET either as it doesn't know anything about JSON.  Alternately, I can take the JSObject returned by the script if I could serialize it to JSON in C#, but JSON.NET doesn't handle these JSObjects.</p>
  
  <p>Here's a code sample:</p>
  
  <pre><code>// using Newtonsoft.Json; // somewhere at the top
  dynamic json = new JObject();
  json.Id = 1;
  json.Name = new JObject();
  json.Name.First = "John";
  json.Name.Last = "Doe";
  json.Dob = new DateTime(1970, 2, 3);
  
  // dynamically construct a script for eval... could be anything... contrived example below.
  var js = new StringBuilder();
  
  // set up a new object, passed from C# world into JScript.NET
  js.AppendLine("var person = " + json.ToString() + ";");
  
  // do something useful
  js.AppendLine("person.FullName = person.Name.First + ' ' + person.Name.Last;");
  
  // return person object... this comes back as JSObject.  Wish I could JSON.stringify!
  js.AppendLine("person;");
  
  // objResult is a JSObject, but how do I get json string???
  dynamic objResult = JSEvaluator.Eval(js.ToString());
  
  // tried JSON.NET, but it doesn't work!
  // var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(objResult);
  </code></pre>
  
  <p>Any help would be greatly appreciated!</p>