在 Javascript - Google 标签管理器中解析 Json

Parse Json in Javascript - Google Tag Manager

我有那个脚本:

function() {
  var publishedDate = "";
  var yoastInfo = JSON.parse(document.head.querySelector('.yoast-schema-graph.yoast-schema-graph--main').innerHTML);
  vars = yoastInfo["@graph"];
  for(var i in vars) {
    if(vars[i]['@type'] === 'WebPage') {
      pubDateRaw=(vars[i]['datePublished']);
      break;
    }
  }
  publishedDate.concat(pubDateRaw.substring(0,4),pubDateRaw.substring(5,7),pubDateRaw.substring(8,10));
  return publishedDate;
}

当我 运行 代码时,它给了我 "" 而不是日期。

这里是 json:

{
  "@context": "https://schema.org",
  "@graph": [   

    {
      "@type": "WebPage",
      "@id": "id234234",
      "url": "https://www.whatevver.com",
      "inLanguage": "de-DE",
      "name": "this is the name",
      "isPartOf": {
        "@id": "id234234
      },
      "primaryImageOfPage": {
        "@id": "id234234"
      },
      "datePublished": "2020-01-14T07:46:12+00:00",
      "dateModified": "2020-01-15T08:04:50+00:00",
      "description": "description "
    },

  ]
}

所以我需要从 json 中提取发布日期。我的代码有什么问题?

编辑

在你们的帮助下,我制作了这个脚本:

function() {
  var publishedDate = "";
  var yoastInfo = JSON.parse(document.head.querySelector('.yoast-schema-graph.yoast-schema-graph--main').innerHTML); 
  vars = yoastInfo["@graph"];
  for(var i in vars) {
    if(vars[i]['@type'] === 'WebPage') {
      publishedDate=(vars[i]['datePublished']); 
    }
  }



  return publishedDate;
}

现在我需要将日期时间 2020-01-14T07:46:12+00:00 缩短为 2020-01-14 什么是最好的解决方案?

EDIT2

在以下位置找到解决方案:To the Solution

给定 JSON :

{
  "@context": "https://schema.org",
  "@graph": [   

    {
      "@type": "WebPage",
      "@id": "id234234",
      "url": "https://www.whatevver.com",
      "inLanguage": "de-DE",
      "name": "this is the name",
      "isPartOf": {
        "@id": "id234234" // MAKE IT AS A STRING
      },
      "primaryImageOfPage": {
        "@id": "id234234"
      },
      "datePublished": "2020-01-14T07:46:12+00:00",
      "dateModified": "2020-01-15T08:04:50+00:00",
      "description": "description "
    },

  ]
}
function() {
  let publishedDate = "";
  const yoastInfo = JSON.parse(document.head.querySelector('.yoast-schema- 
  graph.yoast-schema-graph--main').innerHTML); // I HOPE YOURE ABLE TO EXTRACT THE JSON HERE IN yoastInfo.
  vars = yoastInfo["@graph"];
  for(var i in vars) {
    if(vars[i]['@type'] === 'WebPage') {
      publishedDate=(vars[i]['datePublished']); // YOU ARE GETTING EMPTY STRING BECAUSE YOU'RE SETTING VARIABLE CALLED 'publishedDate' AND SETTING VALUE IN 'pubDateRaw'.
    }
  }
  return publishedDate;
}

请按照代码中的注释进行说明。谢谢 :))

并检查 link 以获得更多说明: https://jsfiddle.net/gahzsrvj/1/