简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM