当JSON Payload具有不同格式时,使用Javascript或jQuery if else语句使用不同的变量

时间:2018-11-20 12:49:16

标签: javascript jquery json

我有一个学校项目,当JSON格式不同时,我必须创建一个“ if else”语句以使用不同的变量。

下面是我要提取并用作车把的有效载荷:

"templateName": "xyzTemplate",
        "payload": {
            "categories": "chocolates",
            "modifier": "chocolate-detail",
            "header": "Your Chocolates",
            "channelType": "W",
            "accounts": [{
                "subTitle": "Sorry, I am having trouble processing your current request.",
                "acctId": "I love chocolates",

                    "type": "Dark Chocolates",
                    "extraParams": {
                        "amountOfChocolates": "4386249702964395",
                        "chocolatesEaten": "27000"

但是,有时有效载荷会变成这样:

"templateName": "xyzTemplate",
    "payload": {
      "categories": "chocolates",
      "modifier": "chocolate-detail",
      "header": "Your Chocolates",
      "channelType": "W",
      "accounts": [
        {
          "subTitle": "Sorry, I am having trouble processing your current request.",
          "acctId": "I love chocolates",
          "account": {
            "type": "Dark Chocolates",
            "extraParams": {
              "amountOfChocolates": "4386249702964395",
                        "chocolatesEaten": "27000"
            },

我想使用以下变量var数据来反映不同的有效负载。示例:

    var alldata = [];
    //if payload has accounts[0].account
    var data = var data = resp.payload.accounts[0].account;
    //else
    var data = resp.payload.accounts[0];

非常感谢您对此提供的帮助。

1 个答案:

答案 0 :(得分:-2)

如果我正确理解了这个问题: 使用“ sub”帐户道具(如果有),否则使用帐户?

const account = resp.payload.accounts[0];
const data = account.account || account;

注意:首选使用'const'和'let'而不是'var'。 (但是您稍后可能会在编程类中看到它:D)