javascriptc#.netjsonjint

Reading JSON objects from javascript file using JINT


I've been supplied with a javascript file containing two JSON objects such as this.

var languages = {"Languages":["English","Cymraeg","Deutsch"]};
var labels = [{"$JOB":["Job","Orchwyl","Auftrag",]},{"$JOB_NO":["Job Number","Rhiforchwyl","Auftragsnummer"]}];

I need to serialise the two JSON objects into something I can manipulate within .NET. I'm using JINT to get the two values from the file like this.

Engine js = new Engine();
js.Execute(fileContents);
languages = js.GetValue("languages");
labels = js.GetValue("labels");

But I can't do anything with the two values now. I can't parse the JSON, the values just come out as a strange object array where I can't actually determine the values.

Any suggestions on how I can get access to the JSON objects?


Solution

  • There is no JSON here. This is javascript code, that creates javascript objects when it's evaluated.

    Now, you can convert that javascript object into a JSON string. The simplest way I found, was to have JINT do it for me, but I'm no expert in Jint, there might be better ways.

    // Run javascript, inside the interpreter, to create JSON strings
    js.Execute("languages = JSON.stringify(languages)");
    js.Execute("labels = JSON.stringify(labels)");
    // Extract the strings from the JS environment, into your c# code as strings
    // Now, you can deserialize them as normal JSON
    var languagesJsonString = js.GetValue("languages").AsString();
    var labelsJsonString = js.GetValue("labels").AsString();