[英]Parse Json in Javascript - Google Tag Manager
I do have that script:我确实有那个脚本:
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;
}
When I run the code, it gives me a ""
instead of the date.当我运行代码时,它给了我一个
""
而不是日期。
here is the json:这是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 "
},
]
}
So i need to extract the datePubished from that json.所以我需要从那个 json 中提取 datePubished。 What is wrong with my code?
我的代码有什么问题?
Edit编辑
With the help of you guys, I made this script:在你们的帮助下,我制作了这个脚本:
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;
}
now I need to cut the dateTime 2020-01-14T07:46:12+00:00
to 2020-01-14
what would be the best solution?现在我需要将日期时间
2020-01-14T07:46:12+00:00
到2020-01-14
什么是最好的解决方案?
EDIT2编辑2
Found the Solution at: To the Solution在以下位置找到解决方案: 到解决方案
Given JSON :给定 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;
}
PLEASE FOLLOW THE COMMENTS IN THE CODE FOR CLARIFICATION.请按照代码中的注释进行澄清。 THANKS :))
谢谢 :))
And check the link for more clarification: https://jsfiddle.net/gahzsrvj/1/并查看链接以获取更多说明: https : //jsfiddle.net/gahzsrvj/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.