简体   繁体   中英

How to insert date inside json in html element

I have json inside meta tag attribute:

<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. 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. You can't execute JavaScript in a data-attribute, data-attributes only stores arbitrary data.

Don't confuse JSON with JavaScript. JSON is language independent and represents objects, is not a programming language.

Run the code and inspect the iframe to check the added date.

 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"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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