How to Parse JSON from a web api in JavaScript - javascript

I am trying to parse this HummingBird api with sample url :
http://hummingbird.me/api/v1/search/anime?query=naruto
However, I do not know how to get each id seperately , or each name seperately. For e.g:-
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = //make this display name
</script>
</body>
</html>
I want the demo element to display the title of the first one in the list. Can anyone tell me how I can possibly do this?

If you use jQuery below is the snippet you can use.
var results = "";
$.get("http://hummingbird.me/api/v1/search/anime?query=naruto",function(data){
results = JSON.parse(data);
});
console.log(results);

Download JQuery from here and put the file next to your html.
Add this element between the html tag and the body
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
Replace document.getElementById("demo").innerHTML = with:
$(document).ready(function(){
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null, function (data) {document.getElementById("demo").innerHTML = data[0].title})
})
JQuery is a JS library that makes life easy.
The function below takes 1 function as an argument and executes it after the page has loaded
$(document).ready()
The next function makes an HTTP GET request and parses the response to js object
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null,...)
The next function gets the title of the first element of data
function (data) {document.getElementById("demo").innerHTML = data[0].title}

mmm try this fiddle i don't know exactly how you read the file but if you get a string do the JSON.parse(STRING) before.
https://jsfiddle.net/79a1abbL/3/

Related

Update a div with jQuery [duplicate]

This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:
page.html:
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('mypage.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('mypage.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<div id="load_tweets"> </div>
</body>
</html>
If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:
http://37.187.90.121:3874/currentsong?sid=1&c=
The output of this source is like this:
Inna - Un Momento
If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?
EDIT1:
ok is a policy problem, how i can resolve it?
EDIT2:+
The proxy php page solution don't work.
I have make this php page:
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>
But i have this error message:
Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Edit3:
The external service give me a javascript to get the information:
window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('<span title="'+r+'">Unavailable</span>'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++<this.settings.poll_limit)&&setTimeout(this.poll_all,this.settings.poll_frequency)},poll_all:function(){window.centovacast.streaminfo._poll_all()},register:function(e,t,n,r){this.registry[t]||(this.registry[t]={charset:n,mountpoint:r,current_song:"",id:{}});var i=e.match(/^cc_strinfo_([a-z]+)_/);i&&(this.registry[t].id[i[1]]=e)},load:function(){var t=e(this).attr("id");if(typeof t!="string")return;var n=t.replace(/^cc_strinfo_[a-z]+_/,""),r="",i="",s=/_cs-([A-Za-z0-9\-]+)$/,o=s.exec(n);o&&(r=o[1],n=n.replace(s,"")),s=/_mp-([A-Za-z0-9\-]+)$/,o=s.exec(n),o&&(i=o[1],n=n.replace(s,"")),window.centovacast.streaminfo.register(t,n,r,i)},run:function(){e(".cc_streaminfo").each(window.centovacast.streaminfo.load),window.centovacast.streaminfo.poll_all()}}});
You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js
Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.
This script give me an output like:
"Radio Name - Author - Title of song"
and this is a link (if you click on it open another page).
I need to get only "Author - Title of song" with no link. Any idea?
Edit4:
I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var div = document.getElementsByClassName('cc_streaminfo')[0];
document.write("w1" + document.getElementsByClassName('cc_streaminfo')[0]);
document.write("w2" + document.getElementsByClassName('cc_streaminfo')[1]);
document.write("w3" + document.getElementsByClassName('cc_streaminfo')[2]);
var container = document.getElementById ("cc_strinfo_summary_radiowhite");
var spans = div.getElementsByTagName("span");
document.write("il mio script: " + spans[0] + "!");
document.write("il mio script: " + container + "!");
//var first_load =
function firstLoad()
{
$('#load_tweets').load('current_g.php?song=ciao');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('current_g.php?song=' + cc_streaminfo).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<br>
<span id="cc_strinfo_summary_radiowhite" class="cc_streaminfo">sss</span>
<div id="load_tweets"> </div>
</body>
</html>
I think this has something to do with CORS. Basically, unless the webpage at 37.187.90.121 explicitly states that it trusts the sources of the domain under which your website is running, your browser will not make the request.
If you are the owner of 37.187.90.121, you can add custom headers to allow inclusion of your response in other webpages.
Check your javascript console of your browser to get more details.
Using jQuery to get (.load()) the contents from a div on another page ( same domain ) to add to a div on the current page is like :
$("#dividoncurrentpage").load("/otherpage.php #dividonotherpage");
Is this what you need ?
It's because:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
mstaessen has explained on the post above.
The alternative solution is: You can create a file called, for example song.php and add the following code.
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong?sid=1&c=");
?>
And update the script to
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('song.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('song.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
Its better to use jQuery $.ajax to get the content. Link
By using $.ajax you have many ways to work around this issue like crossDomain or get the result in Json format by setting the dataType that you will receive from the server to JSON or JSONP

Getting JSON data from a URL in Javascript

I'm trying to read JSON data from a webserver but am lost. I don't get any errors but my code doesn't display anything either. Here's the sample
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?', function(json) { //this works. but doesn't display any alerts or data
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo&callback=?', function(json) { //this works. notice the callback
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function(json) { //this also works
alert("good");
alert(JSON.stringify(json));
console.log(JSON.stringify(json));
});
});
</script>
</head>
<body>
<div id = 'placeholder'></div>
</body>
</html>
If you notice I've tried 3 $.getJSON statements with different URLs, 2 work, but the one with the key in the url doesn't display any alert upon success.
The "example" url "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?" works fine (when example replaced with an actual domain) if posted in the browser, and returns JSON data as
[{"FCCID":"52601","Calls":"WAWZ","StnFreq":"99.1","MktID":"18","StnOwner":"Pillar of Fire","StnNameHD1":"Star 99.1","StnDescrHD1":"Great Christian Music!","StnContentHD1":"Music","StnGenreHD1":"Religious","StnAltGenreHD1":null,"StnLangHD1":"English","StnWebsiteHD1":"www.star991fm.com","StnFBHD1":"facebook.com\/star991fm","StnTwitterHD1":"http:\/\/twitter.com\/star991fm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(800) 791-0991","StnRebrHD1":"none","StnFeatHD1":"0","StnAEHD1":"Unknown","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD1":"","StnNameHD2":"WAWZ-HD2","StnDescrHD2":"Teaching and Preaching","StnContentHD2":"News\/Talk","StnGenreHD2":"Religious","StnAltGenreHD2":null,"StnLangHD2":"English","StnWebsiteHD2":"www.star991fm.com","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"(800) 791-0991","StnRebrHD2":"none","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD2":"","StnNameHD3":"WAWZ-HD3","StnDescrHD3":"The Energy","StnContentHD3":"Music","StnGenreHD3":"Religious","StnAltGenreHD3":null,"StnLangHD3":"English","StnWebsiteHD3":"www.star991fm.com","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"(800) 791-0991","StnRebrHD3":"none","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"none","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""},{"FCCID":"49587","Calls":"WDHA","StnFreq":"105.5","MktID":"20","StnOwner":"Greater Media","StnNameHD1":"","StnDescrHD1":"The Rock of New Jersey","StnContentHD1":"Music","StnGenreHD1":"Rock","StnAltGenreHD1":null,"StnLangHD1":null,"StnWebsiteHD1":"www.wdha.com","StnFBHD1":"www.facebook.com\/pages\/1055-WDHA","StnTwitterHD1":"http:\/\/twitter.com\/wdhafm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(973) 455-1055","StnRebrHD1":"","StnFeatHD1":"0","StnAEHD1":"Live","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/e\/b\/eb72e37fe8f446bd44d783b1b641fff0.png","StnAudioHD1":"","StnNameHD2":"","StnDescrHD2":"","StnContentHD2":"","StnGenreHD2":null,"StnAltGenreHD2":null,"StnLangHD2":null,"StnWebsiteHD2":"","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"","StnRebrHD2":"","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"","StnAudioHD2":"","StnNameHD3":"","StnDescrHD3":"","StnContentHD3":"","StnGenreHD3":null,"StnAltGenreHD3":null,"StnLangHD3":null,"StnWebsiteHD3":"","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"","StnRebrHD3":"","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""}]
Please let me know if I'm doing something stupid here. I'm completely new to Javascript and just starting to learn.
$.get( "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?", function( data ) {
console.log(data.FCCID);
}, "json" );
This should help you. You can do what you want with the returned data.

Setting data attribute for object element in html

i have an object element in my html body to show an Active reports which exports to a .pdf file. I need to use javascript to automatically print the pdf out to the client's default printer and then save the pdf to the server:
<script language="javascript" type="text/javascript">
// <!CDATA[
function PrintPDF() {
pdf.click();
pdf.setActive();
pdf.focus();
pdf.PrintAll();
}
// ]]>
....
<body onload="return PrintPDF();">
<form id="form1" runat="server">
<object id="pdfDoc" type="application/pdf" width="100%" height="100%" data="test.aspx?PrintReport=yes&SavePDF=yes"/>
</form>
</body>
With the data hard-code in the object tag, everything run without a problem.
The problem now is that I need to pass querystring to this page dynamically. I tried to set the attribute data in the javsacript to pass the querystring. The querystring value passed successfully, but the data attribute does not seem to be set. I get a blank page.
pdf.setAttribute("data","test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum);
Does anyone have a clue how I can set the data attribute dynamically to pass in querystring?
Thanks,
var pdfObj = document.getElementById('pdfDoc');
pdfObj.data="test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum;
As far as the data attribute you're doing everything fine. Here are some examples:
http://jsfiddle.net/3SxRu/
I think your problem might be more to do with the order of execution. What does your actual code look like? Are you writing over the body onLoad function or something?
Also, I assume using the data attribute is a requirement. HTML5 defines data-*. This attribute isn't really valid. Again, maybe your system requires it.
I suspect that things are happening out of order. Try waiting until the onload event of the window before adding the embed.
Also, I suggest using a script like PDFObject to handle the embedding since it is a reliable way to embed PDF across all the various browsers out there. For example you might have something like the following:
<html>
<head>
<title>PDFObject example</title>
<script type="text/javascript" src="pdfobject.js"></script>
<script type="text/javascript">
window.onload = function (){
// First build the link to the PDF raw data ("bits")
// getQueryStrings assumes something like http://stackoverflow.com/questions/2907482/how-to-get-the-query-string-by-javascript
var queryStrings = getQueryStrings();
var reportNameParamValue = queryStrings["reportName"];
var pdfBitsUrl = "getReportPdfBits.aspx?reportName=" + reportNameParamValue;
// just in case PDF cannot be embedded, we'll fix the fallback link below:
var pdfFallbackLink = document.getElementById("pdfFallbackAnchor");
pdfFallbackLink.href = pdfFallbackLink;
// now perform the actual embed using PDFObject script from http://pdfobject.com
var success = new PDFObject( {
url: pdfBitsUrl;
}).embed();
};
</script>
</head>
<body>
<p>It appears you don't have Adobe Reader or PDF support in this web
browser. <a id="pdfFallbackAnchor" href="sample.pdf">Click here to download the PDF</a></p>
</body>

Pass values from Servlet to an onload JavaScript function in a JSP

I am using the following code in my Servlet to set the Attribute confirmMsg :
req.setAttribute("confirmMsg", "Update Values");
This I'm forwarding to the JSP
RequestDispatcher rd = req.getRequestDispatcher("displayDetails.jsp");
rd.forward(req, resp);
In my JSP, I need to display the message when the page loads.
<body onload = "showConfirmMsg();">
// .....
</body>
What should I do in the following function, so as to show the message onload itself?
function showConfirmMsg() {
// Code to show the alert box onload
}
Using jQuery, you can do something like:
<script>
$(function() {
var msg = "${confirmMsg}";
// do something with your message :)
});
</script>
<body onload=""> isn't very clean :)
Just let JSP/EL print the JS code accordingly so that the browser retrieves valid HTML/JS code.
E.g.
<body onload="showConfirmMsg('${confirmMsg}');">
with
function showConfirmMsg(confirmMsg) {
// ...
}
If you can't guarantee that the ${confirmMsg} doesn't contain JS-special characters like ', newlines, etc then you need to escape it beforehand by for example Apache Commons Lang StringEscapeUtils#escapeJavaScript().
There is no need of calling a function on load, instead use JSP scriplet.
<body>
<%=request.getAttribute("confirmMsg")%>
</body>

How can I read a JSON in the script-tag from JavaScript?

I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don't know if it's best to do it with jQuery or without.
$(function() {
// read JSON
alert("the json is:")
})
I would change the script declaration to this:
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
Note type and id fields. After that
var data = JSON.parse(document.getElementById('data').textContent);
will work just fine in all browsers.
The type="application/json" is needed to prevent browser from parsing it while loading.
And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.
I ended up with this JavaScript code to be independent of jQuery.
var jsonElement = document.getElementById('json-script-tag');
var myObject = JSON.parse(jsonElement.textContent);
To read JSON in <script id="myJSON"> use
var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON
You can also use methods to point to the script like document.scripts[0]
//var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
JSON.parse($('script[src="mysript.js"]').html());
or invent some other method to identify the script.
Maybe instead of .html() you might need .text(). Not sure. Try them both.

Categories