1

新手问题在这里。我正在调用使用 node-soap 在 node.js 中进行 Web 服务调用并获得类似于以下内容的响应:

{ AuthenticateResult:
   { PrimaryKeyId: '0',
     ValidateOnly: false,
     OperationResult: 'Succeeded',
     SessionId: 'abc45235435345' } }

如果 OperationResult 为“成功”,从响应中提取 SessionId 值的最佳方法是什么?我猜我可以用 indexof 和 substring 来做到这一点,但即使对于像我这样的新手来说,这听起来也不是一个好的解决方案。

4

1 回答 1

0

假设输入存储为字符串,并且是一致的(即,冒号左侧没有引号的 JSON),您可以使用正则表达式将其转换为 JSON 字符串,然后使用JSON.parse().

var input = "{ AuthenticateResult: {\n"
            + "PrimaryKeyId: '0',\n"
            + "ValidateOnly: false,\n"
            + "OperationResult: 'Succeeded',\n"
            + "SessionId: 'abc45235435345' } }";

// This replaces word: with "word": and ' with "
var json = input.replace(/(\w+):/g, '"$1":').replace(/'/g, '"');

// This here's the object you want
var obj = JSON.parse(json);

// Just printing out the JSON so you know it works.
document.getElementById('result').innerHTML = json;
<pre id="result"></pre>

于 2015-10-28T22:34:40.677 回答