簡體   English   中英

在 Javascript 中解析 Json - Google 標簽管理器

[英]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 中提取 datePubished。 我的代碼有什么問題?

編輯

在你們的幫助下,我制作了這個腳本:

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:002020-01-14什么是最好的解決方案?

編輯2

在以下位置找到解決方案: 到解決方案

給定 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;
}

請按照代碼中的注釋進行澄清。 謝謝 :))

並查看鏈接以獲取更多說明: https : //jsfiddle.net/gahzsrvj/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM