Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ankurngm opened this issue Nov 1, 2012 · 1 comment

Comments

@ankurngm
Copy link

ankurngm commented Nov 1, 2012

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
Copy link
Author

ankurngm commented Nov 1, 2012

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!

@ankurngm ankurngm closed this as completed Nov 1, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant