0

我在Yahoo! Messenger API文档以查看如何获取访问令牌,我发现了这一点:

调用如下所示:

https://login.yahoo.com/WSLogin/V1/get_auth_token?&login=username&passwd=mypassword&oauth_consumer_key=consumerkey

此调用的结果是单个值,即RequestToken

RequestToken=jUO3Qolu3AYGU1KtB9vUbxlnzfIiFRLP...

然后此令牌用于第二个请求,该请求将 PART 交换为 OAuth 访问令牌。您可以在此处找到有关获取访问令牌的标准方法的更多信息。

我猜这个结果是一个标准的结果,但我不知道这是一个什么样的数据。我的意思是它不是 XML 或 JSON。

我想将这样的字符串转换为 JSON:

{
    RequestToken: "jU0..."
}

是否有任何标准转换器/解析器或者我必须构建一个?


此外,另一个请求可能如下所示:

Error=MissingParameters
ErrorDescription=Sorry, try again with all the required parameters.

我想把它转换成 JSON:

{
   Error: "MissingParameters",
   ErrorDescription: "Sorry, try again with all the required parameters."
}

构建这样一个解析器会很容易,但我不想重新发明轮子。

4

1 回答 1

0

我决定编写自己的函数。如果有解析此类字符串的标准算法,请发表评论。

/*
 *  Transform a string like this:
 *
 *  "Field1=123
 *  Field2=1234
 *  Field3=5"
 *
 *  into an object like this:
 *
 *  {
 *      "Field1": "123",
 *      "Field2": "1234",
 *      "Field3": "5",
 *  }
 *
 * */
function parseResponse (str) {

    // validate the provided value
    if (typeof str !== "string") {
        throw new Error("Please provide a string as argument: " + 
                                                 JSON.stringify(str));
    }

    // split it into lines
    var lines = str.trim().split("\n");

    // create the object that will be returned
    var parsedObject = {};

    // for every line
    for (var i = 0; i < lines.length; ++i) {
        // split the line
        var splits = lines[i].split("=")
            // and get the field
            , field = splits[0]
            // and the value
            , value = splits[1];

        // finally set them in the parsed object
        parsedObject[field] = value;
    }

    // return the parsed object
    return parsedObject;
};
于 2013-11-26T13:04:25.723 回答