简体   繁体   English

如何使用 JavaScript 访问特定的 json 元素

[英]How to access a specific json element with JavaScript

I have a html-page with multiple json-elements and want to show content from one of them (jsonld of type book) into the page.我有一个带有多个 json 元素的 html 页面,并且想要将其中一个(类型为 book 的 jsonld)的内容显示到页面中。

As long as there is only the needed json on the page, everything works fine.只要页面上只有所需的 json,一切正常。 But i can't figure out how to adress the correct json once there is an additional json.但是一旦有额外的 json,我就无法弄清楚如何处理正确的 json。

Do i need to make an additional loop with parsing the json an check for the type (but how to target the element then), or is there an easy and performant way (if-condition maybe?).我是否需要通过解析 json 来创建一个额外的循环来检查类型(但是如何定位元素),或者是否有一种简单高效的方法(如果条件可能?)。

Any ideas, help and hints would be highly appreciated.任何想法、帮助和提示将不胜感激。

 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 &amp; 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\üsenhagen 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\üpper" }, "bookFormat": "Paperback", "isbn": "978-3959672993", "url": "https://www.freie-lektoren.de/?post_type=buecher&#038;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>

Loop through the JSON objects, and get the one you need:循环遍历 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 &amp; 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\üsenhagen 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\üpper" }, "bookFormat": "Paperback", "isbn": "978-3959672993", "url": "https://www.freie-lektoren.de/?post_type=buecher&#038;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>

With the snippet above you can parse any number of JSON objects in your HTML, and work with them like a JavaScript object - query them, filter them, assign its values to DOM elements, etc.使用上面的代码片段,您可以解析 HTML 中任意数量的 JSON 对象,并像处理 JavaScript 对象一样使用它们 - 查询它们、过滤它们、将其值分配给 DOM 元素等。

just give them a name!给他们一个名字!

 <script> var json1 = { "@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 &amp; 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\üsenhagen 28" }, { "@type": "PostalAddress", "addressCountry": null, "addressLocality": "Berlin", "addressRegion": "Berlin", "postalCode": "10179", "streetAddress": "Engeldamm 66" } ] }; var json2 = { "@context": "http://schema.org", "@type": "Book", "name": "Der Tote vom Elbhang", "author": { "@type": "Person", "name": "Anke K\üpper" }, "bookFormat": "Paperback", "isbn": "978-3959672993", "url": "https://www.freie-lektoren.de/?post_type=buecher&#038;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>

then parse them by their names :然后通过他们的名字解析它们:

 function codeAddress() { var jsonld1 = JSON.parse(json1); //your functions }

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

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