简体   繁体   English

使用JINT从JavaScript文件读取JSON对象

[英]Reading JSON objects from javascript file using JINT

I've been supplied with a javascript file containing two JSON objects such as this. 我已经提供了一个JavaScript文件,其中包含两个这样的JSON对象。

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. 我需要将两个JSON对象序列化为可以在.NET中操作的对象。 I'm using JINT to get the two values from the file like this. 我正在使用JINT这样从文件中获取两个值。

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. 我无法解析JSON,这些值只是作为一个奇怪的对象数组出现,而我实际上无法确定这些值。

Any suggestions on how I can get access to the JSON objects? 关于如何获取JSON对象的任何建议?

There is no JSON here. 这里没有JSON。 This is javascript code, that creates javascript objects when it's evaluated. 这是javascript代码,在评估时会创建javascript对象。

Now, you can convert that javascript object into a JSON string. 现在,您可以将该JavaScript对象转换为JSON字符串。 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. 我发现的最简单的方法是让JINT为我做,但是我不是Jint的专家,可能会有更好的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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