【问题标题】:How to get value from JSON object如何从 JSON 对象中获取值
【发布时间】:2020-02-17 10:40:06
【问题描述】:

在我的 Web 应用程序中,Web API 返回以下 JOSN 对象。

[ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

我需要通过传递 templateID 从每个 JSON 节点获取 Body 值。问题是你可以看到这个 JSON 在某些地方有\r\n。我需要获取每个节点的 Body 值。例如,如果我通过 1,我需要得到 sample date hete hee. Name,如果通过 2,我需要 you soon.,我该怎么做?

我试过这个。但它不起作用

var data2 = [ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

function usersBasedOnIDs(isShow,field){

    var filtered=data2.filter(function(item){
        return item[field] == isShow;         
    });
    console.log(filtered);
}

usersBasedOnIDs(1,'templateID');

【问题讨论】:

  • item[field] == isShow; 没有值为1 的模板。所以它只打印空数组
  • “问题是你可以看到这个 JSON 在某些地方有 \r\n。” - 这与 anything 有什么关系?
  • 您的 json 在其字符串中编码了 json。整个事情不应该只是 json 吗?
  • 您只是在寻找错误的领域。您想检查 templateID 中包含的内容,但您将 'template' 传递给您的函数以动态访问该属性……
  • @CodeManiac 我更新了它。现在它返回"{ "Body": "sample date hete hee." }" 我怎样才能得到Body 值

标签: javascript arrays json regex replace


【解决方案1】:
item[field] == isShow;  

您没有任何对象满足此条件,我想您想根据 ID 过滤元素,然后查看它的主体值

var data2 = [{
    "templateID": 1,
    "template": "{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
  },
  {
    "templateID": 2,
    "template": "{ \"Body\": \"you soon.\" }"
  }
]

function usersBasedOnIDs(isShow, field) {

  var filtered = data2.filter(function(item) {
    return item[field] == isShow;
  });
  console.log(filtered && JSON.parse(filtered[0].template).Body);
}

usersBasedOnIDs(1, 'templateID');

【讨论】:

    【解决方案2】:

    试试这个

    var x = [ 
       { 
          "templateID":1,
          "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
       },
       { 
          "templateID":2,
          "template":"{ \"Body\": \"you soon.\" }"
       }
    ]
    for(let i=0;i<x.length;i++){
      let y = x[i].template;
      console.log(JSON.parse(y).Body);
    }
    

    【讨论】:

      【解决方案3】:
      function usersBasedOnIDs(templateId) {
          let result = data2.find(function(item) {
              return item.templateId === templateId;
          });
          if(result === undefined) {
              return;
          } else {
              return JSON.parse(result.template).Body;
          }
      }
      
      console.log(usersBasedOnIDs(1));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多