2

I am trying to use JScript.NET to do dynamic code evaluation. I have a simple JScript.NET eval method that handles that:

public static object Eval(string javascript) {
  return Microsoft.JScript.Eval.JScriptEvaluate(javascript, Microsoft.JScript.Vsa.VsaEngine.CreateEngine());
}

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 out from my javascript program into my C# caller. When I return a object, what I get back is a JSObject (http://msdn.microsoft.com/en-us/library/microsoft.jscript.jsobject.aspx). 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.

Here's a code sample:

// 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);

Any help would be greatly appreciated!

mattmc3
  • 17,595
  • 7
  • 83
  • 103
  • possible Duplicate- check out this answer http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4 – MethodMan Dec 17 '12 at 21:40
  • 1
    I really can't understand why you need these javascript or StringBuilder stuff. Serializing an object to json is a simple thing. – L.B Dec 17 '12 at 21:40
  • @DJ KRAZE - No. Maybe I could be more clear. I can turn my C# object into JSON just fine using JSON.NET. When I do the JavaScript eval(), I can't get a JSON string back out of Jscript.NET. I spent 1/2 an hour looking on SO before posting. Actually running the sample code might help in comprehension. – mattmc3 Dec 17 '12 at 21:43
  • 1
    Instead of describing *"how you want to do it"*, asking *"what you really want do to"* may give you better answers. – L.B Dec 17 '12 at 22:16
  • I would like to get a arbitrary JSON string from an object back out of a JScript.NET eval. – mattmc3 Dec 17 '12 at 22:24
  • Have you tried adding something akin to JSON2 to your eval environment? – Michael B Oct 11 '13 at 16:00
  • @MichaelB - No, but if you share a working example that does what I'm attempting, and it's the best answer then the bounty is yours. – mattmc3 Oct 13 '13 at 18:19

1 Answers1

3

Is this what you're looking for? Essentially I just took json2.min.js (per @Michael B's suggestion in the comments) and added it to the javascript as a first order of business. This enables you to stringify your object as you wanted and send the JSON string back to the C# world. From there you can convert it back to a JObject and get the data from it or manipulate it further. A complete program based on your example code follows:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main(string[] args)
    {
        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();

        // Add JSON2.min.js so we can stringify
        js.AppendLine(@"var JSON;JSON||(JSON={}),(function(){""use strict"";function i(n){return n<10?""0""+n:n}function f(n){return o.lastIndex=0,o.test(n)?'""'+n.replace(o,function(n){var t=s[n];return typeof t==""string""?t:""\\u""+(""0000""+n.charCodeAt(0).toString(16)).slice(-4)})+'""':'""'+n+'""'}function r(i,e){var h,l,c,a,v=n,s,o=e[i];o&&typeof o==""object""&&typeof o.toJSON==""function""&&(o=o.toJSON(i)),typeof t==""function""&&(o=t.call(e,i,o));switch(typeof o){case""string"":return f(o);case""number"":return isFinite(o)?String(o):""null"";case""boolean"":case""null"":return String(o);case""object"":if(!o)return""null"";n+=u,s=[];if(Object.prototype.toString.apply(o)===""[object Array]""){for(a=o.length,h=0;h<a;h+=1)s[h]=r(h,o)||""null"";return c=s.length===0?""[]"":n?""[\n""+n+s.join("",\n""+n)+""\n""+v+""]"":""[""+s.join("","")+""]"",n=v,c}if(t&&typeof t==""object"")for(a=t.length,h=0;h<a;h+=1)typeof t[h]==""string""&&(l=t[h],c=r(l,o),c&&s.push(f(l)+(n?"": "":"":"")+c));else for(l in o)Object.prototype.hasOwnProperty.call(o,l)&&(c=r(l,o),c&&s.push(f(l)+(n?"": "":"":"")+c));return c=s.length===0?""{}"":n?""{\n""+n+s.join("",\n""+n)+""\n""+v+""}"":""{""+s.join("","")+""}"",n=v,c}}typeof Date.prototype.toJSON!=""function""&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+""-""+i(this.getUTCMonth()+1)+""-""+i(this.getUTCDate())+""T""+i(this.getUTCHours())+"":""+i(this.getUTCMinutes())+"":""+i(this.getUTCSeconds())+""Z"":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o=/[\\\""\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,u,s={""\b"":""\\b"",""\t"":""\\t"",""\n"":""\\n"",""\f"":""\\f"",""\r"":""\\r"",'""':'\\""',""\\"":""\\\\""},t;typeof JSON.stringify!=""function""&&(JSON.stringify=function(i,f,e){var o;n="""",u="""";if(typeof e==""number"")for(o=0;o<e;o+=1)u+="" "";else typeof e==""string""&&(u=e);t=f;if(f&&typeof f!=""function""&&(typeof f!=""object""||typeof f.length!=""number""))throw new Error(""JSON.stringify"");return r("""",{"""":i})}),typeof JSON.parse!=""function""&&(JSON.parse=function(n,t){function r(n,i){var f,e,u=n[i];if(u&&typeof u==""object"")for(f in u)Object.prototype.hasOwnProperty.call(u,f)&&(e=r(u,f),e!==undefined?u[f]=e:delete u[f]);return t.call(n,i,u)}var i;n=String(n),e.lastIndex=0,e.test(n)&&(n=n.replace(e,function(n){return""\\u""+(""0000""+n.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(n.replace(/\\(?:[""\\\/bfnrt]|u[0-9a-fA-F]{4})/g,""@"").replace(/""[^""\\\n\r]*""|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,""]"").replace(/(?:^|:|,)(?:\s*\[)+/g,"""")))return i=eval(""(""+n+"")""),typeof t==""function""?r({"""":i},""""):i;throw new SyntaxError(""JSON.parse"");})})()");

        // 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 stringified person object
        js.AppendLine("JSON.stringify(person);");

        // objResult is a JScript.ConcatString
        dynamic objResult = Eval(js.ToString());

        // Get our manipulated object back to the C# world
        json = JsonConvert.DeserializeObject(objResult.ToString());

        // Print out the Full Name which was added inside the JS
        Console.WriteLine(json.FullName);
    }

    public static object Eval(string javascript)
    {
        return Microsoft.JScript.Eval.JScriptEvaluate(javascript, Microsoft.JScript.Vsa.VsaEngine.CreateEngine());
    }
}

Output:

John Doe
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300