最优雅的方式是使用 JSON 解析器。我个人的偏好是使用htmlfile COM 对象导入 IE 的 JSON 解析器。
import System;
var str:String = '{"params":{"key1":"foo","key2":"bar","key3":"baz"}}',
htmlfile = new ActiveXObject('htmlfile');
// force htmlfile COM object into IE9 compatibility
htmlfile.IHTMLDocument2_write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
// clone JSON object and methods into familiar syntax
var JSON = htmlfile.parentWindow.JSON,
// deserialize your JSON-formatted string
obj = JSON.parse(str);
// access JSON values as members of a hierarchical object
Console.WriteLine("params.key2 = " + obj.params.key2);
// beautify the JSON
Console.WriteLine(JSON.stringify(obj, null, '\t'));
编译、链接和运行结果如下控制台输出:
params.key2 = bar
{
"params": {
"key1": "foo",
"key2": "bar",
"key3": "baz"
}
}
另外,至少还有一个couple of .NET namespaces 提供将对象序列化为 JSON 字符串以及将 JSON 字符串反序列化为对象的方法。不过,不能说我是粉丝。 JSON.parse() 和 JSON.stringify() 的 ECMAScript 符号肯定比任何胡须疯狂 going on at Microsoft 更容易,也更不陌生。
虽然我当然不建议将 JSON(或任何其他分层标记,如果有帮助的话)作为复杂的文本进行抓取,但 JScript.NET 将处理许多熟悉的 Javascript 方法和对象,包括正则表达式对象和正则表达式替换字符串。
sed 语法:
echo $a | sed -r 's/("key2"):"[^"]*"/\1:"replaced"/g'
JScript.NET 语法:
print(a.replace(/("key2"):"[^"]*"/, '$1:"replaced"'));
JScript.NET 与 JScript 和 JavaScript 一样,也允许调用 lambda 函数进行替换。
print(
a.replace(
/"(key2)":"([^"]*)"/,
// $0 = full match; $1 = (key2); $2 = ([^"]*)
function($0, $1, $2):String {
var replace:String = $2.toUpperCase();
return '"$1":"' + replace + '"';
}
)
);
...或者使用RegExp对象的exec()方法提取key2的值:
var extracted:String = /"key2":"([^"]*)"/.exec(a)[1];
print(extracted);
不过,请注意这一点,因为如果没有匹配项,则检索 [1] 的结果中的元素 exec() 将导致 index-out-of-range 异常。可能想要if (/"key2":/.test(a)) 或添加try...catch。或者更好的是,按照我之前所说的将 JSON 反序列化为一个对象。