Display JSON dictionary in browser using html - javascript

So I've looked and looked and looked at different answers on StackExchange and other web forums and I still don't understand this.
I've got a .json file that contains the information from an excel document.
I want to display it on a web browser -> the easiest way to do this seems to be writing it in html.
How do I open the JSON file with html?? I'm happy with having the entire JSON file displayed on the html script but I would love to be able to set is as a variable and pull things out of it like a normal JSON object.
I have the code below for making a table which is what I want to do - but the real JSON object is in a separate file.
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}
var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i=0;i<books.Scala.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
To clarify: The above code works great; but I want to do it with the contents of a .json file saved on my local drive.
Thanks in advance.

I see that you didn't include the jquery tag, so I'll provide a couple of vanilla javascript solutions:
If the file is located at an accesible directory, you can pull the data like this:
Define your JSON object as follows:
Original:
[{ "name" : "John", "date" : "01-27-2014" }]
Modified into javascript:
var data = '[{ "name" : "John", "date" : "01-27-2014" }]';
And save it to a plain text document named mydata.json.js, for example (the double extension has nothing to do with the content itself).
So it becomes a valid javascript file and you can load it on your html like this:
<script src="mydata.json.js"></script>
And you can use your data var on your HTML normally.
Or use this if you don't have the document locally or the above approach is too makeshifty for you. Refer to this question. Quoting:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (success) {
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
Update:
You can create a global var, e.g. data, to store the retrieved JSON and redefine the function as follows:
if (xhr.readyState === 4 && xhr.status === 200) {
data = JSON.parse(xhr.responseText); // This now contains the JSON object.
}
Note that xhr.responseText is the raw JSON string and the JSON.parse(…) functions returns a javascript collection with the data of that JSON.

You need to pull JSON using AJAX.
This will require you to have web server running, as some browsers, e.g. Chrome will block requests to local resources. Also have in mind that AJAX & JSON request will work only within the same domain (same origin policy), or you will have to use JSONP.
If you can use jQuery (hence it's an easiest way), look here: http://api.jquery.com/jquery.getjson/
$.getJSON( "test.json", function( data ) {
$.each( data, function( key, val ) {
// do something
});
});
Hope it helps!

You can do this without the need for ajax by using a server side language such as PHP. You can include the raw JSON into a Javascript variable.
Below is an example of including the file with PHP:
<script>
//JSON included via PHP
var books = <?php include('books.json'); ?>;
</script>
The file "books.json" would contain your raw JSON information:
{ "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}

Related

Print linked to the logical value

Good morning I wanted help for a code that can use a logical value example:
`` `
function provaIf2(){
var A2=SpreadsheetApp.getActive().getRange('A2').getValue();
var C4=SpreadsheetApp.getActive().getRange('C4').getValue();
if(A2=="") SpreadsheetApp.getActive().getRange('B2').activate();
else if(A2<C4) Print the sheet
else if(A2==C4) Print the sheet
else SpreadsheetApp.getActive().getRange('B3').activate();
}
If you want to print a document using Apps Script, you will have to use Google Cloud Print.
As explained in this article here, you will have to create an Apps Script project in which you include the OAuth2 library. Then you need to get the Google Cloud Print service, send the request and last but not least, print the document.
The below code snippet is used to print the document with the desired options:
function printGoogleDocument(docID, printerID, docName) {
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "NO_DUPLEX"
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket)
};
Reference: Automatically Print Files Placed in Drive with Google Cloud Print and Apps Script.

Get data from script code

I want to get data from a website, can I get url data from code?
Example code:
<script type="application/json" id="store">
{
"url":{"host":"localhost"},
"resources":
{
"xxfff":
{
"stream":
{
"streamId":"","duration":212714,"videos":
[
{
"url":"www.test.com"
},
{
"url":"www.site.net"
}
]
}
}
},
}
</script>
I just want to get "www.site.net" from script code, is it possible?
This is absolutely possible. To demonstrate, I'm going to show you how you could create such an element in the first place, and then how to retrieve the data. If you are manually putting the code in the script tag, I would suggest stringifying it first.
let src = document.createElement('script');
src.setAttribute('id', 'store');
let json = {
url : {
host : "localhost"
},
resources : {
xxfff : {
stream : {
streamId : "",
duration : 212714,
videos : [
{
url : "www.test.com"
},
{
url : "www.site.net"
}
]
}
}
}
};
json = JSON.stringify(json);
src.innerText = json;
const body = document.getElementsByTagName('body')[0];
const footer = document.getElementById('footer');
body.insertBefore(src, footer);
// Now you have created the element,
// so you reverse the process to get your data
src = document.getElementById('store');
json = src.innerText;
json = JSON.parse(json);
let sites = json.resources.xxfff.stream.videos;
sites.map(site => console.log(site.url));
If you mean you have this script tag somewhere in your webpage, you can read it as any other tag, using innerHTML (right in the first line of this snippet):
var json=document.getElementById("store").innerHTML;
var data=JSON.parse(json);
var videos=data.resources.xxfff.stream.videos;
var table=document.getElementById("tbl");
videos.forEach(function(urlObj){
var td=document.createElement("td");
td.innerHTML=urlObj.url;
var tr=document.createElement("tr");
tr.appendChild(td);
table.appendChild(tr);
});
<script type="application/json" id="store">
{
"url":{"host":"localhost"},
"resources":
{
"xxfff":
{
"stream":
{
"streamId":"","duration":212714,"videos":
[
{
"url":"www.test.com"
},
{
"url":"www.site.net"
}
]
}
}
}
}
</script>
<table border="1" id="tbl"></table>
On a side note, there was a surplus comma in your original post (right before the last closing curly brace) which made the entire thing invalid. I removed it in the hopes of it was just some copy-paste issue, perhaps you had more fields just wanted to cut the post shorter.
Also, if you generate this data immediately into the page, you could just let it be "normal" script, and surround it with a simple var data= and ; pair. Then it would be a variable already, without the need for parsing.

Load more json data onClick

I have been trying to create a webpage that appends JSON data into a ul. The problem is that the JSON file has more than 600 values.
I would like to limit the number of values retrieved, say 10 and then add a 'load more' button to append more, eg. 10 more, to it and so on. Here's my code.
<body onload="loadUser(20)">
<ul id="placeholder"></ul>
function loadUser(arg) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'people.json', true);
xhr.onload = function() {
if (this.status == 200) {
var users = JSON.parse(this.responseText);
for (var i = 0; i < arg; i++) {
var output = `<li class="list_item">${users[i].name</li>`;
document.getElementById('placeholder').innerHTML += output;
}
document.getElementById('placeholder').innerHTML += '<button onclick="loadmore()">load more</button>';
}
}
xhr.send();
}
// JSON Example:
[{
"id": 1,
"name": "Mithu Mondal",
"email": "mithu#bla.com"
},
{
"id": 2,
"name": "Frankenstien",
"email": "frank#gmail.com"
}
]
Here's the link: https://www.mithuation.ml/jsonExample/
Thanks in Advance.
When you perform an AJAX request (XMLHTTPRequest) it loads the entire file. There is no way to have the browser load a partial file.
If you do not plan to use a database (which would allow you to query a certain number of items at a time), I recommend that you split your data up into several JSON files. When you perform the XMLHTTPRequest, you will only retrieve a subset of the data. For the next request, you will retrieve the next file and thus get the next set of data.
I guess this is what you are searching for Lazy.js. It will parse as much of the JSON as possible, asynchronously.
Import the libraries:
<script type="text/javascript" src="lazy.js"></script>
<!-- optional: if you want support for DOM event and AJAX-based sequences: -->
<script type="text/javascript" src="lazy.browser.js"></script>
If your want to retrieve 10 item at a time:
var response = JSON.parse(this.responseText);
var result = Lazy(response)
.take(10);
document.getElementById('placeholder').innerHTML += output;

JSON data to HTML using .html()

The code below is commented throughout. It is my understanding that I'm retrieving the JSON data and passing it to the 'results' div in my HTML view. This actually returns nothing, and it's difficult to debug because I can't output anything to the console.
// Here is how the final url should look:
// api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b
var weatherSearch = '';
// weather-search is my html form id. On submit, send the input
// (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});
// getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
q: weatherSearch,
APPID: '2e76bb25aa22d34ca062d764f4f3114b'
};
// This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
// Request data using url and params above.
// Does $.getJSON format the url properly?
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
});
}
function showWeather(weather) {
// Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);
}
Here is the associated HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="openweather.js"></script>
</head>
<body>
<form id="weather-search">
<input type="text" value="" id="weatherQuery" />
<input type="submit" />
</form>
<div id="weatherResults">
</div>
</body>
</html>
Here's a codepen for the program
This answer demonstrates multiple ways to request and view data.
The code snippet below queries the web service using either jQuery or plain javascript. The returned data is displayed on the screen using JSON.stringify() and Google Prettify. The data is also sent to the console. Interestingly, the OpenWeatherMap service makes a good guess when the city name is misspelled.
The problem with OP's code appears to be this line: showWeather(data.items); which tries to display an object as html.
Run the snippet to try
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=2e76bb25aa22d34ca062d764f4f3114b';
// plain javascript version
function getWeather(city) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '&q=' + city, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
showData( data );
}
}
xhr.send();
}
// jQuery version
function getWeather2( city ) {
$.getJSON(url + '&q=' + city, showData );
}
// display json weather data
function showData( data ) {
window.city.value = data.name;
window.stdout.innerHTML = JSON.stringify(data, false, ' ');
window.stdout.className = 'prettyprint';
PR.prettyPrint();
if (window.console) window.console.log( data );
}
// sample data
getWeather('Berlin');
input {border: 1px solid black;}
button {width: 8em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.js?autoload=false&skin=sunburst&lang=js"></script>
Enter City: <input id="city" >
<button onclick="getWeather(window.city.value)">Use JS</button>
<button onclick="getWeather2(window.city.value)">Use jQuery</button>
<pre id="stdout" class="prettyprint"></pre>
You can use console.log or the dom to print messages for debugging. You can run a callback like this to find out if a request fails, this will tell you more infomation:
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Using the complete URL (http://api.openweathermap.org/data/2.5/weather/?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b) directly in a browser returns some JSON with data about chicago -- but that JSON does NOT contain an item property. Thus, your data.items is null and nothing is shown.
Just check what you actually get from the browser and adopt your code accordingly (e.g. data.name would give you "Chicago", or simply use showWeather(data); to show all JSON you got).

How to use jquery to decode the return json object?

I trid to use an upload plugin for jQuery.
http://valums.com/ajax-upload/
When I set the returning respond type to json, firefox will popup a dialog asking how I like to handle the returning json object.
People have asked the same question at the upload script's author's page but no answer so far. Hopefully javascript guys here can figure out how we can handle this.
Thanks.
<script type= "text/javascript">
/*<![CDATA[*/
$(document).ready(function(){
/* example 1 */
var button = $('#button1'), interval;
new AjaxUpload(button, {
//action: 'upload-test.php', // I disabled uploads in this example for security reasons
action: '/posts/upload_images/',
name: 'myfile',
responseType: 'json',
onSubmit : function(file, ext){
// change button text, when user selects file
button.text('Uploading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 13){
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response){
var json = response;
alert(json);
button.text('Upload');
window.clearInterval(interval);
// enable upload button
this.enable();
// add file to the list
// $('<li></li>').appendTo('#example1 .files').text(json.response_text);
$('<li></li>').appendTo('#example1 .files').text(file);
}
});
});
/*]]>*/
</script>
http://api.jquery.com/jQuery.parseJSON/
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This jQuery plugin makes it simple to convert to and from JSON: http://code.google.com/p/jquery-json/
Also, you might be interested in this comment on the blog post you referenced:
Sorry to spam your blog post (which is great), but I thought I’d mention that I found the problem:
For whatever reason, the response always has <pre> tags around the entire response when the response is of type plain/text. That was causing the eval() call to fail. My current solution was just to strip those tags off before the eval() call and now everything works. Not a great solution but at least I can keep working for now.
I was looking for a solution for the same script and stumbled upon this page. I didn't found a solution online so here's how I fixed it:
# upload-file.php:
replace
echo "success".$cc;
with
echo json_encode(array(
status' => 'success',
'id' => $picid,
'image' => $imgurl
));
# front end:
replace
var bb=response.substr(0,7)
var idd=response.replace('success',' ');
var idb =idd.replace(/^\s*|\s*$/g,'');
if(bb==="success")
{
$('<span></span>').appendTo('#files').html('<img src="images/'+file+'" alt="" width="120" height="120" style="margin:5px;" />').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(file).addClass('error');
}
with
var what = jQuery.parseJSON(response);
if(what.status == 'success')
{
$('<span id='+what.id+'></span>').appendTo('#files').html('<img src="'+what.image+'" alt="" width="120" height="120" style="margin:5px;" /><br>Delete').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(response).addClass('error');
}
And to actually answer this question.
jQuery.parseJSON(response);
does..
This may be it, I don't know because I know nothing about that plugin, but you may need to take a look at the response type you are setting on the server-side of things; you should set the HTTP response to have a content/MIME type of something like "text/plain", "text/javascript" or "application/javascript" - see if that fixes your problem.

Categories

Resources