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

44 views
Skip to first unread message

Ankur Nigam

unread,
Nov 1, 2012, 8:47:22 AM11/1/12
to iro...@googlegroups.com
Hi,

I am new to IronJS and 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<FunctionObject>("HandleJson");
            var result = handleJson.Call(o.Globals, jsonString).Unbox<string>();
            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 which isn't available server side.
I can use jQuery method obj = $.parseJSON(jsonStr); as well but don't know how to load jQuery file.

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

Thanks.

Ankur Nigam

unread,
Nov 1, 2012, 12:20:27 PM11/1/12
to iro...@googlegroups.com
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!
Reply all
Reply to author
Forward
0 new messages