1

初心者の質問はこちら。node-soap を使用して node.js で Web サービス呼び出しを行っており、次のような応答を取得しています。

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

OperationResult が「Succeeded」の場合、応答から 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 に答える