起因
在修复结构化数据时,尝试使用原生 JS 去操作含在 html 标签内的 Json
简易实现方法
Json Example
1
2
3
4
5
6
7
8
|
<script id="myjsonid" type="application/ld+json">
{
"headline": "",
"datePublished": "",
"dateModified": "",
"image": "" // 不能添逗号否则 parse 报错
}
</script>
|
第一种方法
1
2
|
const script = document.getElementById("myjsonid");
script.firstChild.nodeValue = '{"headline": "myheadline", "datePublished": "1024-1024-1024", "dateModified": "1024-1024-1024", "image": "https://i.loli.net/2019/10/31/9kjzeQfiy43HK2B.jpg"}'; // Completely replace it
|
第二种方法
1
2
|
const script = document.getElementById("myjsonid");
script.textContent = '{"headline": "myheadline", "datePublished": "1024-1024-1024", "dateModified": "1024-1024-1024", "image": "https://i.loli.net/2019/10/31/9kjzeQfiy43HK2B.jpg"}'; // Completely replace it
|
Output
1
|
<script id="myjsonid" type="application/ld+json">{"headline": "myheadline", "datePublished": "1024-1024-1024", "dateModified": "1024-1024-1024", "image": "https://i.loli.net/2019/10/31/9kjzeQfiy43HK2B.jpg"}</script>
|
这样毫无疑问很麻烦,如果只想要改一对键值的话,全部替换岂不要命?
上面方法只是操作了 Json 字符串,但是 JS 娘还有各种操作 Json 对象的方法,那么可以将其转化为对象然后再偷梁换柱一波
最终实现
1
2
3
4
5
6
7
|
const script = document.getElementById("myjsonid");
const obj = JSON.parse(script.firstChild.nodeValue);
obj.headline = "myheadline";
obj.datePublished = "1024-1024-1024";
obj.dateModified = "1024-1024-1024";
obj.image = "https://i.loli.net/2019/10/31/9kjzeQfiy43HK2B.jpg";
script.firstChild.nodeValue = JSON.stringify(obj); // Also use script.textContent
|