javascript - 如何使用 JavaScript 访问特定的 json 元素
问题描述
我有一个包含多个 json 元素的 html 页面,并希望将其中一个(类型为 book 的 jsonld)的内容显示到页面中。
只要页面上只有所需的 json,一切正常。但是一旦有一个额外的json,我就无法弄清楚如何处理正确的json。
我是否需要通过解析 json 来检查类型(但如何定位元素),或者是否有一种简单且高效的方法(如果条件可能?)。
任何想法、帮助和提示将不胜感激。
function codeAddress() {
var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerHTML);
document.getElementById('name').innerHTML = jsonld.name;
document.getElementById('buch-link').href =jsonld.sameAs;
document.getElementById('buch-link').title =jsonld.publisher.name + " - " + jsonld.author.name + " - " + jsonld.name;
document.getElementById('publisher').innerHTML = jsonld.publisher.name;
document.getElementById('year').innerHTML = jsonld.copyrightYear;
document.getElementById('format').innerHTML = jsonld.bookFormat;
document.getElementById('pages').innerHTML = jsonld.numberOfPages;
document.getElementById('isbn').innerHTML = jsonld.isbn;
}
window.onload = codeAddress;
jQuery('#buchbeschreibung').parent('.panel-grid').prepend(jQuery('#leistungen:parent'));
<div class="book-data">
<p>
<a id="buch-link" href="#" target="_blank" title="name"><strong id="name"></strong></a><br />
<span id="publisher"></span>, <span id="year"></span><br />
<span id="format"></span>, <span id="pages"></span> Seiten<br />
ISBN: <span id="isbn"></span><br />
</p>
</div>
<script type="application/ld+json">{
"@context": "http://schema.org",
"@type": "LocalBusiness",
"image": "https://www.freie-lektoren.de/wp-content/uploads/Nehmen-Sie-Platz-e1546854168810.jpg",
"priceRange": "$$",
"telephone": "+49-30-306442-60",
"additionalType": "http://www.productontology.org/doc/Lector",
"name": "Freie Lektoren Obst & Ohlerich",
"logo": "https://www.freie-lektoren.de/wp-content/uploads/FreieLektoren_Logo.svg",
"description": null,
"openingHours": "Mo-Fr 9:00-15:30",
"geo": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": null,
"longitude": null
},
"geoRadius": "750"
},
"url": "https://www.freie-lektoren.de",
"sameAs": [
"https://www.facebook.com/freielektoren/"
],
"contactPoint": {
"@type": "ContactPoint",
"telephone": "+49-30-306442-60",
"contactType": "customer service",
"email": "obst@freie-lektoren.de",
"contactOption": "",
"areaServed": [
"AT",
"DE",
"CH"
],
"availableLanguage": [
"English",
"German"
]
},
"address": [
{
"@type": "PostalAddress",
"addressCountry": "Germany",
"addressLocality": "Gumtow",
"addressRegion": "Brandenburg",
"postalCode": "16866",
"streetAddress": "Br\u00fcsenhagen 28"
},
{
"@type": "PostalAddress",
"addressCountry": null,
"addressLocality": "Berlin",
"addressRegion": "Berlin",
"postalCode": "10179",
"streetAddress": "Engeldamm 66"
}
]
}</script>
<script type="application/ld+json">{
"@context": "http://schema.org",
"@type": "Book",
"name": "Der Tote vom Elbhang",
"author": {
"@type": "Person",
"name": "Anke K\u00fcpper"
},
"bookFormat": "Paperback",
"isbn": "978-3959672993",
"url": "https://www.freie-lektoren.de/?post_type=buecher&p=10186",
"sameAs": "https://www.harpercollins.de/products/der-tote-vom-elbhang-9783959678445",
"publisher": {
"@type": "Organization",
"name": "HarperCollings"
},
"numberOfPages": "336",
"copyrightYear": "2019",
"genre": "Krimi",
"inLanguage": "de-DE"
}</script>
解决方案
遍历 JSON 对象,并获取您需要的对象:
function codeAddress() {
// I used document.querySelectorAll() to grab all the ld+json items on the page
const jsons = document.querySelectorAll('script[type="application/ld+json"]')
const jsonld = []
// transform the grabbed items' content to array of JSON objects
jsons.forEach(e => jsonld.push(JSON.parse(e.innerHTML)))
// return the created array
return jsonld
}
// calling the DOM modification function with the array of
// parsed JSON objects, and querying it for @type === 'Book'
// so only return the JSON object that has a type of Book
window.onload = setBookInformation(codeAddress().find(e => e['@type'] === 'Book'));
// a separate function to handle DOM modifications
function setBookInformation(json) {
document.getElementById('name').innerHTML = json.name;
document.getElementById('buch-link').href = json.sameAs;
document.getElementById('buch-link').title = json.publisher.name + " - " + json.author.name + " - " + json.name;
document.getElementById('publisher').innerHTML = json.publisher.name;
document.getElementById('year').innerHTML = json.copyrightYear;
document.getElementById('format').innerHTML = json.bookFormat;
document.getElementById('pages').innerHTML = json.numberOfPages;
document.getElementById('isbn').innerHTML = json.isbn;
}
// jQuery('#buchbeschreibung').parent('.panel-grid').prepend(jQuery('#leistungen:parent'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="book-data">
<p>
<a id="buch-link" href="#" target="_blank" title="name"><strong id="name"></strong></a><br />
<span id="publisher"></span>, <span id="year"></span><br />
<span id="format"></span>, <span id="pages"></span> Seiten<br /> ISBN: <span id="isbn"></span><br />
</p>
</div>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "LocalBusiness",
"image": "https://www.freie-lektoren.de/wp-content/uploads/Nehmen-Sie-Platz-e1546854168810.jpg",
"priceRange": "$$",
"telephone": "+49-30-306442-60",
"additionalType": "http://www.productontology.org/doc/Lector",
"name": "Freie Lektoren Obst & Ohlerich",
"logo": "https://www.freie-lektoren.de/wp-content/uploads/FreieLektoren_Logo.svg",
"description": null,
"openingHours": "Mo-Fr 9:00-15:30",
"geo": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": null,
"longitude": null
},
"geoRadius": "750"
},
"url": "https://www.freie-lektoren.de",
"sameAs": [
"https://www.facebook.com/freielektoren/"
],
"contactPoint": {
"@type": "ContactPoint",
"telephone": "+49-30-306442-60",
"contactType": "customer service",
"email": "obst@freie-lektoren.de",
"contactOption": "",
"areaServed": [
"AT",
"DE",
"CH"
],
"availableLanguage": [
"English",
"German"
]
},
"address": [{
"@type": "PostalAddress",
"addressCountry": "Germany",
"addressLocality": "Gumtow",
"addressRegion": "Brandenburg",
"postalCode": "16866",
"streetAddress": "Br\u00fcsenhagen 28"
},
{
"@type": "PostalAddress",
"addressCountry": null,
"addressLocality": "Berlin",
"addressRegion": "Berlin",
"postalCode": "10179",
"streetAddress": "Engeldamm 66"
}
]
}
</script>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Book",
"name": "Der Tote vom Elbhang",
"author": {
"@type": "Person",
"name": "Anke K\u00fcpper"
},
"bookFormat": "Paperback",
"isbn": "978-3959672993",
"url": "https://www.freie-lektoren.de/?post_type=buecher&p=10186",
"sameAs": "https://www.harpercollins.de/products/der-tote-vom-elbhang-9783959678445",
"publisher": {
"@type": "Organization",
"name": "HarperCollings"
},
"numberOfPages": "336",
"copyrightYear": "2019",
"genre": "Krimi",
"inLanguage": "de-DE"
}
</script>
使用上面的代码片段,您可以解析 HTML 中任意数量的 JSON 对象,并像 JavaScript 对象一样使用它们——查询它们、过滤它们、将其值分配给 DOM 元素等。
推荐阅读
- python - RuntimeError:“字节”未实现“reflection_pad2d”
- qt - 如何像在 MSVS 中一样从应用程序输出在 QT Creator 中导航?
- javascript - Vue - 等到加载必要的数据
- python - 在 Python 中动态关闭 Excel 文件
- python-3.x - 如果字符串存在,则过滤熊猫数据框
- python - 如何查找和读取 get_referrers 的输出以及为什么它的长度与 python 中的 getrefcount 不同
- javascript - 静态图像未通过 javascript 加载
- python-3.x - 如何使用 TensorFlow 对象检测 API 开始训练 mask_rcnn_inception_v2_coco 模型(TF 1.15.2)
- php - 如何在 opencart 订单添加文件的电子邮件顶部添加图像&
- python - 在 Excel 中模拟 SUMIFS 函数时无法在 Python 中收到正确的结果