fholm / IronJS

IronJS - A JavaScript implementation for .NET
http://ironjs.wordpress.com
Apache License 2.0
680 stars 79 forks source link

How to parse JSON(send as string parameter) to a method in JavaScript function #93

Closed ankurngm closed 11 years ago

ankurngm commented 11 years ago

Hi,

I am facing difficulty parsing JSON in JavaScript method.

My C# Code

string jsonString = “{\”Name\”: \”Ankur\”, \”Sex\”: \”Male\”}”; var o = new IronJS.Hosting.CSharp.Context(); o.ExecuteFile(@”C:\CustomScript.js”); var handleJson = o.Globals.GetT(“HandleJson”); var result = handleJson.Call(o.Globals, jsonString).Unbox(); Console.WriteLine(result);

JavaScript method in CustomScript.js

function HandleJson(jsonStr) { obj = JSON.parse(jsonStr); return obj.Name; }

Everytime I do this, I get error message saying “ReferenceError: JSON is not defined”

Guess, “JSON.parse” method is native to browser and isn’t available server side. I can use jQuery method obj = $.parseJSON(jsonStr); as well but don’t know how to load jQuery file at server.

Any thoughts on what I am doing wrong or how to fix it?

Thanks.

ankurngm commented 11 years ago

I have found the fix to it.

JSON.parse is an unknown JS method at Server(which is why we were getting the error)... So, we need to add/load "json2.js" before CustomScript.js file and then we will be good.

json2.js can be downloaded from following location: https://github.com/douglascrockford/JSON-js

Following is my updated code.

Updated C# Code

        string jsonString = "{\"Name\": \"Ankur\", \"Sex\": \"Male\"}";
        var o = new IronJS.Hosting.CSharp.Context();
        o.ExecuteFile(@"C:\json2.js");
        o.ExecuteFile(@"C:\CustomScript.js");
        var handleJson = o.Globals.GetT<FunctionObject>("HandleJson");
        var result = handleJson.Call(o.Globals, jsonString).Unbox<string>();
        Console.WriteLine(result);

No changes are required in CustomScript.js

Cheers!