简体   繁体   English

如何在HTML元素的json中插入日期

[英]How to insert date inside json in html element

I have json inside meta tag attribute: 我在meta标签属性内有json:

<head>
  <title>PLD Interaction pattern</title>
    <meta data-pageObject='{
      "page": {
        "pageInfo":   {
          "pageID": "12345",
          "pageName": "smartphones:samsung-galaxy-s-5",
          "prevPageName": "phones",
          "version": "1.15",
          "language": "en-US",
          "geoRegion": "US",
          "responsiveState": "desktop",
          "timeStamp": "+new Date()+", //Insert date here
          "currencyCode": "USD"
        }
      }
    }' id="metaJson">
</head>

I need to insert date into timestamp key. 我需要在时间timestamp密钥中插入日期。 I tried to escape using ' but its showing syntax error. 我尝试使用'进行转义'但显示语法错误。 Is there a way to escape it and insert date? 有没有办法逃脱它并插入日期?

You will have to use JavaScript to get the string, convert from JSON to an object, add the date and later stringify the object into the data-attribute again. 您将必须使用JavaScript来获取字符串,从JSON转换为对象,添加日期,然后再将该对象字符串化为数据属性。 You can't execute JavaScript in a data-attribute, data-attributes only stores arbitrary data. 您不能在数据属性中执行JavaScript,数据属性只能存储任意数据。

Don't confuse JSON with JavaScript. 不要将JSON与JavaScript混淆。 JSON is language independent and represents objects, is not a programming language. JSON与语言无关,并且代表对象,不是编程语言。

Run the code and inspect the iframe to check the added date. 运行代码并检查iframe以检查添加日期。

 var metaJson = document.getElementsByTagName('meta').item(property='metaJson'); var data = metaJson.getAttribute('data-pageObject'); data = JSON.parse(data); data.date = new Date(); metaJson.setAttribute('data-pageObject', JSON.stringify(data)); 
  <meta name="metaJson" data-pageObject='{ "page": { "pageInfo": { "pageID": "12345", "pageName": "smartphones:samsung-galaxy-s-5", "prevPageName": "phones", "version": "1.15", "language": "en-US", "geoRegion": "US", "responsiveState": "desktop", "currencyCode": "USD" } } }' id="metaJson"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM